forked from sheetjs/docs.sheetjs.com
		
	
		
			
	
	
		
			38 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Java
		
	
	
	
	
	
		
		
			
		
	
	
			38 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Java
		
	
	
	
	
	
|  | 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);" +
 | ||
|  |       "for(var i = 0; i < out.length; i++) out[i] = (b[i] + 256) & 0xFF;" +
 | ||
|  |       "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);
 | ||
|  |   }
 | ||
|  | }
 |