Java 如何使用ApachePOI在已存在的excel文件中创建新工作表
我正在尝试为现有excel文件创建新的excel工作表,但遇到错误org.apache.poi.EmptyFileException。下面是我的代码Java 如何使用ApachePOI在已存在的excel文件中创建新工作表,java,excel,apache-poi,Java,Excel,Apache Poi,我正在尝试为现有excel文件创建新的excel工作表,但遇到错误org.apache.poi.EmptyFileException。下面是我的代码 public static void main(String[] args) { XSSFWorkbook workbook = null; File file = new File("C:/Users/NewUser/Desktop/Sample.xls"); FileOutputStrea
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();
}
}
如何克服该异常,以及如何在一个excel文件中创建多个工作表
fileOut = new FileOutputStream(file);
删除您的文件,但它仍然存在(file.exists()==true)
)。因此,当您使用WorkbookFactory.create(…)
打开一个空文件时,您会得到一个EmptyFileException
如果在使用
WorkbookFactory.create(…)
之前调试程序并停止,您将看到Sample.xls的文件大小为零
我认为您的问题是,新文件(…)
在编写之前不会创建文件。因此,您进入else
-分支,创建一个没有文件的新工作簿。您应该调试代码并检查这个假设。@Srinivas:如果我的答案解决了您的问题,最好将其标记为已接受的答案。