I am trying to write List data into multiple excel sheet in one work book. like for first list, the code will create new workbook and create new sheet for list[1], for second list it will create new sheet in existing workbook and so on. so i wrote below code. but it doesnt work and i am able to see only first sheet for list[1]. can someone help me to provide any alternate resolutions?
the below code i have written
ArrayList<List<String>> tempresultdata=this.getSummaryList();
HSSFWorkbook workbook = new HSSFWorkbook();
String fileName="Path\\To\\XLS";
File file = new File(fileName);
FileOutputStream out;
if(!file.exists()) // This will create new workbook with new sheet if it doesnt exists{
HSSFSheet mySheet = workbook.createSheet(sheetname);
writeExcel(mySheet,tempresultdata);
} else // This add new sheet to above created workbook {
try {
HSSFWorkbook myWorkBook = (HSSFWorkbook) WorkbookFactory.create(file);
workbook=myWorkBook;
HSSFSheet mySheet = (HSSFSheet) workbook.createSheet(sheetname);
writeExcel(mySheet,tempresultdata);
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try{
out = new FileOutputStream(fileName,true);
workbook.write(out);
out.close();
}catch(Exception e){
e.printStackTrace();
}
Thanks, Priyank Shah
If file does not exist then this code creates new file and also creates sample sheet1 but if file exists then it adds new sheet to existing excel file.
HSSFWorkbook workbook = null;
File file = new File(context.getExternalFilesDir(null), "Sample.xls");
FileOutputStream fileOut = new FileOutputStream(file);
if (file.exists()) {
try {
workbook = (HSSFWorkbook)WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
}
HSSFSheet sheet = workbook.createSheet("Sample sheet2");
}
else{
workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet1");
}
workbook.write(fileOut);
fileOut.close();
Looks like you are only writing out the sheet
not the workbook
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With