docs.sheetjs.com/docz/static/v8/SheetJSJavet.java
2024-06-20 03:30:34 -04:00

31 lines
1.3 KiB
Java

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import com.caoccao.javet.interop.V8Host;
import com.caoccao.javet.interop.V8Runtime;
public class SheetJSJavet {
public static void main(String[] args) throws Exception {
/* initialize */
V8Runtime v8Runtime = V8Host.getV8Instance().createV8Runtime();
/* read script file */
v8Runtime.getExecutor("var global = (function(){ return this; }).call(null);").executeVoid();
v8Runtime.getExecutor(new Scanner(SheetJSJavet.class.getResourceAsStream("/xlsx.full.min.js")).useDelimiter("\\Z").next()).executeVoid();
System.out.println(v8Runtime.getExecutor("'SheetJS Version ' + XLSX.version").executeString());
/* read spreadsheet bytes */
v8Runtime.getGlobalObject().set("i8", Files.readAllBytes(Paths.get(args[0])));
v8Runtime.getExecutor("var u8 = new Uint8Array(i8.buffer, i8.byteOffset, i8.length);").executeVoid();
/* parse workbook */
v8Runtime.getExecutor("var wb = XLSX.read(u8, {type: 'array'})").executeVoid();
/* get first worksheet as CSV */
v8Runtime.getExecutor("var ws = wb.Sheets[wb.SheetNames[0]];").executeVoid();
String res = v8Runtime.getExecutor("XLSX.utils.sheet_to_csv(ws)").executeString();
System.out.println(res);
}
}