[英]How to create new sheet in already existed excel file using apache poi
I am trying to create a new excelsheet for the existing excel file, but i am getting error org.apache.poi.EmptyFileException . 我正在尝试为现有的excel文件创建一个新的excelsheet,但是出现了org.apache.poi.EmptyFileException错误。 Below is my code
下面是我的代码
public static void main(String[] args)
{
XSSFWorkbook workbook = null;
File file = new File("C:/Users/NewUser/Desktop/Sample.xls");
FileOutputStream fileOut = null;
try
{
fileOut = new FileOutputStream(file);
if (file.exists()) {
try {
workbook = (XSSFWorkbook)WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (EncryptedDocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
XSSFSheet sheet = workbook.createSheet("Sample sheet2");
}
else{
workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sample sheet1");
}
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
try {
workbook.write(fileOut);
System.out.println("File Created Succesfully");
fileOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How to overcome with that exception and how to create multiple sheets with in a single excel file? 如何克服这种例外情况,以及如何在单个excel文件中创建多个工作表?
fileOut = new FileOutputStream(file);
erases your file, but it still exists ( file.exists() == true)
). 删除您的文件,但它仍然存在(
file.exists() == true)
)。 So you are opening an empty file when using WorkbookFactory.create(...)
and you get an EmptyFileException . 因此,使用
WorkbookFactory.create(...)
时,您正在打开一个空文件,并且得到EmptyFileException 。
If you debug your prog and stop before the use of WorkbookFactory.create(...)
you will see a zero file size for Sample.xls
. 如果在使用
WorkbookFactory.create(...)
之前调试程序并停止,则Sample.xls
文件大小Sample.xls
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.