Workbook
class has “createSheet” method which takes sheet name and position it will
occupy in the workbook.
Ex:
WritableSheet
sheet = workbook.createSheet("sheet1", 0);
Above
statement creates a sheet named “sheet1” and occupies first position.
Make
sure whatever the operation, you performs on writable sheet, you called below
methods before closing.
workbook.write();
workbook.close();
If
you call close() without calling write() first, a completely empty file will be
generated.
public class WorkBookNotInitializedException extends RuntimeException{ WorkBookNotInitializedException(){ super("work book is not initialized"); } }
import java.io.IOException; import jxl.*; import jxl.write.*; import java.io.File; public class XLSWritableUtils { WritableWorkbook workbook = null; public XLSWritableUtils(String fileName){ try { workbook = Workbook.createWorkbook(new File(fileName)); } catch (IOException ex) { ex.printStackTrace(); } } private void checkWorkbookInitialized(){ if(workbook == null) throw new WorkBookNotInitializedException(); } public void createSheet(String sheetName, int index){ checkWorkbookInitialized(); workbook.createSheet(sheetName, index); } public void close(){ checkWorkbookInitialized(); try{ workbook.write(); workbook.close(); } catch(Exception e){ } } }
public class TestUtils { public static void main(String[] args) { String fileName = "data.xls"; XLSWritableUtils utils = new XLSWritableUtils(fileName); utils.createSheet("employee", 0); utils.close(); } }
Run
TestUtils, it creates file “data.xls” and sheet name “employee”.
No comments:
Post a Comment