如何使用apache poi在已存在的excel文件中创建新工作表

问题描述 投票:0回答:1

我正在尝试为现有的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");
        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文件中创建多个工作表?

java excel apache-poi
1个回答
1
投票
fileOut = new FileOutputStream(file);

删除你的文件,但它仍然存在(file.exists() == true))。所以当你使用WorkbookFactory.create(...)时你打开一个空文件,你得到一个EmptyFileException。

如果你调试你的编程并在使用WorkbookFactory.create(...)之前停止,你会看到Sample.xls的文件大小为零。

© www.soinside.com 2019 - 2024. All rights reserved.