package com.smtscript.lib.jsexcel; import java.io.File; import org.mozilla.javascript.NativeArray; import org.mozilla.javascript.Wrapper; import jxl.Workbook; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import com.smtscript.run.ScriptRunScope; import com.smtscript.run.ScriptRunScope.FileInfo; public class JSExcelWriter { protected ScriptRunScope _parentScope; protected WritableWorkbook _workbook; public JSExcelWriter(ScriptRunScope parentScope, String fileName) throws Exception { _parentScope = parentScope; _workbook = Workbook.createWorkbook(new File(fileName)); } public JSExcelWriter(ScriptRunScope parentScope, String fileName, FileInfo fileInfo) throws Exception { _parentScope = parentScope; Workbook wbTemp = Workbook.getWorkbook(fileInfo.open()); try { _workbook = Workbook.createWorkbook(new File(fileName), wbTemp); } finally { wbTemp.close(); } } public JSExcelWriterSheet createSheet(String name, int index) { if(index < 0) index = _workbook.getSheets().length; WritableSheet sheet = _workbook.createSheet(name, index); return new JSExcelWriterSheet(sheet, this); } public void close() throws Exception { _workbook.write(); _workbook.close(); } public NativeArray getSheetNames() { return new NativeArray(_workbook.getSheetNames()); } public NativeArray getSheets() { WritableSheet[] sheets = _workbook.getSheets(); JSExcelWriterSheet[] rdSheets = new JSExcelWriterSheet[sheets.length]; for(int i = 0; i < sheets.length; i ++) { rdSheets[i] = newSheet(sheets[i]); } return new NativeArray(rdSheets); } public JSExcelWriterSheet readSheet(Object id) throws Exception { if(id instanceof Wrapper) id = ((Wrapper)id).unwrap(); if(id instanceof Double) id = (int)(double)((Double)id); WritableSheet sheet; if(id instanceof String) sheet = _workbook.getSheet((String)id); else if(id instanceof Integer) sheet = _workbook.getSheet((Integer)id); else throw new Exception("unsupport id type : " + id.getClass().getName()); if(sheet == null) throw new Exception("can't find sheet :" + id.toString()); return newSheet(sheet); } protected JSExcelWriterSheet newSheet(WritableSheet sheet) { return new JSExcelWriterSheet(sheet, this); } }