Reputation: 15
I am trying to create a new excelsheet for the existing excel file, but i am getting error 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?
Upvotes: 0
Views: 1163
Reputation: 623
fileOut = new FileOutputStream(file);
erases your file, but it still exists (file.exists() == true)
). So you are opening an empty file when using WorkbookFactory.create(...)
and you get an EmptyFileException.
If you debug your prog and stop before the use of WorkbookFactory.create(...)
you will see a zero file size for Sample.xls
.
Upvotes: 1