docs.sheetjs.com/docz/static/nashorn/SheetJSNashorn.java

38 lines
1.4 KiB
Java
Raw Permalink Normal View History

2023-03-28 04:57:47 +00:00
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class SheetJSNashorn {
public static void main(String[] args) throws Exception {
/* initialize */
ScriptEngine engine = (new ScriptEngineManager()).getEngineByName("javascript");
/* read script file */
engine.eval("var global = (function(){ return this; }).call(null);");
engine.eval(new Scanner(SheetJSNashorn.class.getResourceAsStream("/shim.min.js")).useDelimiter("\\Z").next());
engine.eval(new Scanner(SheetJSNashorn.class.getResourceAsStream("/xlsx.full.min.js")).useDelimiter("\\Z").next());
engine.eval("print('SheetJS Version ' + XLSX.version);");
/* read spreadsheet bytes */
engine.put("bytes", Files.readAllBytes(Paths.get(args[0])));
/* convert signed byte array to JS Uint8Array or unsigned byte array */
engine.eval("function b2a(b) {" +
"var out = typeof Uint8Array == 'function' ? new Uint8Array(b.length) : new Array(b.length);" +
2023-05-22 08:06:09 +00:00
"for(var i = 0; i < out.length; i++) out[i] = b[i] & 0xFF;" +
2023-03-28 04:57:47 +00:00
"return out;" +
"}" +
"var u8a = b2a(bytes)");
/* parse workbook */
engine.eval("var wb = XLSX.read(u8a, {type: 'array'})");
/* get first worksheet as CSV */
engine.eval("var ws = wb.Sheets[wb.SheetNames[0]];");
Object res = engine.eval("XLSX.utils.sheet_to_csv(ws)");
System.out.println(res);
}
}