如何将新表添加到使用Apache POI现有的Excel工作簿? [英] How to add new sheets to existing excel workbook using apache POI?
问题描述
我试图列表数据写入到多个Excel工作表在一个工作簿。像第一个列表中,code将创造新的工作簿,并创建新的目录表[1],第二个名单会造成现有工作簿中新的工作表等。所以我写了下面code。但它不工作,我能够看到清单[1]仅第一页。有人可以帮我提供任何备用的决议?
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?
下面code我写
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();
}
谢谢,
Priyank沙阿
Thanks, Priyank Shah
推荐答案
如果文件不存在,那么这个code创建新的文件,还创建示例工作表Sheet1,但如果文件存在,那么它增加了新的工作表,以现有的Excel文件。
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();
这篇关于如何将新表添加到使用Apache POI现有的Excel工作簿?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!