创建一个新的.xls文件,如果它不存在,如果存在,则修改它[Apache POI]

时间:2016-10-05 15:46:54

标签: java excel apache-poi

我正在使用Apache POI来创建和修改excel文件。我希望我的程序创建一个具有给定名称的新.xls文件,如果该目录中不存在该文件。但是,如果它存在,我希望我的程序只打开该.xls文件并进行修改。

我的程序能够创建一个新的.xls文件,但每当我尝试将文件作为HSSFWorkbook打开时,程序会发出一个错误,指出“无效的头部签名;读取0x0000000000000000,预期为0xE11AB1A1E011CFD0 - 您的文件似乎不是一个有效的OLE2文档“

我用来创建新文件的代码是:

         File excelFile = new File("Test.xls");
         excelFile.createNewFile();
         wb = new HSSFWorkbook(new FileInputStream(excelFile.getName())); // Throws the error right here [wb is an HSSFWorkbook object from the Apache POI Library]

请注意,如果目录中已存在具有该名称的.xls文件,并且我只使用FileOutputStream对象,则它会成功地将所有必需的数据写入文件中。

我用来在excel文件中编写的代码是:

        FileOutputStream fileout = new FileOutputStream("Test.xls", true);
        wb.write(fileout);
        fileout.close();
        wb.close(); // wb is an HSSFWorkbook object from the Apache POI Library

具有完整堆栈跟踪的错误消息是:

  

org.apache.poi.poifs.filesystem.NotOLE2FileException:无效的标题
  签名;读取0x0000000000000000,预期0xE11AB1A1E011CFD0 - 您的   文件似乎不是有效的OLE2文档   org.apache.poi.poifs.storage.HeaderBlock。(HeaderBlock.java:162)     在   org.apache.poi.poifs.storage.HeaderBlock。(HeaderBlock.java:112)     在   org.apache.poi.poifs.filesystem.NPOIFSFileSystem。(NPOIFSFileSystem.java:302)     在   org.apache.poi.hssf.usermodel.HSSFWorkbook。(HSSFWorkbook.java:393)     在   org.apache.poi.hssf.usermodel.HSSFWorkbook。(HSSFWorkbook.java:374)     在   prototpye_2.FrameJScraperTool.processWorkbook(FrameJScraperTool.java:224)     在prototpye_2.FrameJScraperTool.run(FrameJScraperTool.java:54)at   prototpye_2.JFrameTest $ Open.actionPerformed(JFrameTest.java:123)at at   javax.swing.AbstractButton.fireActionPerformed(未知来源)at   javax.swing.AbstractButton $ Handler.actionPerformed(Unknown Source)at   javax.swing.DefaultButtonModel.fireActionPerformed(未知来源)at   javax.swing.DefaultButtonModel.setPressed(未知来源)at   javax.swing.AbstractButton.doClick(未知来源)at   javax.swing.plaf.basic.BasicMenuItemUI.doClick(未知来源)at at   javax.swing.plaf.basic.BasicMenuItemUI $ Handler.mouseReleased(未知   来自java.awt.AWTEventMulticaster.mouseReleased(未知来源)     在java.awt.Component.processMouseEvent(未知来源)at   javax.swing.JComponent.processMouseEvent(未知来源)at   java.awt.Component.processEvent(未知来源)at   java.awt.Container.processEvent(未知来源)at   java.awt.Component.dispatchEventImpl(未知来源)at   java.awt.Container.dispatchEventImpl(未知来源)at   java.awt.Component.dispatchEvent(未知来源)at   java.awt.LightweightDispatcher.retargetMouseEvent(未知来源)at   java.awt.LightweightDispatcher.processMouseEvent(未知来源)at   java.awt.LightweightDispatcher.dispatchEvent(未知来源)at   java.awt.Container.dispatchEventImpl(未知来源)at   java.awt.Window.dispatchEventImpl(未知来源)at   java.awt.Component.dispatchEvent(未知来源)at   java.awt.EventQueue.dispatchEventImpl(未知来源)at   java.awt.EventQueue.access $ 500(未知来源)at   java.awt.EventQueue $ 3.run(未知来源)at   java.awt.EventQueue $ 3.run(未知来源)at   java.security.AccessController.doPrivileged(Native Method)at   java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(未知   来源)at   java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(未知   来自)java.awt.EventQueue $ 4.run(未知来源)at   java.awt.EventQueue $ 4.run(未知来源)at   java.security.AccessController.doPrivileged(Native Method)at   java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(未知   来自)java.awt.EventQueue.dispatchEvent(未知来源)at   java.awt.EventDispatchThread.pumpOneEventForFilters(未知来源)     at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)     在java.awt.EventDispatchThread.pumpEventsForHierarchy(未知   来自java.awt.EventDispatchThread.pumpEvents(未知来源)     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)at   java.awt.EventDispatchThread.run(未知来源)

此外,当生成此错误时,直到在目录中创建的.xls文件,但它的大小为0 KB,如果我们尝试打开该文件,则会抱怨该文件已损坏。 excel中出现以下提示:

Prompt That comes up in excel when you try to open the generated .xls

让我知道是否有更好的方法来实现我想要做的事情,即如果.xls文件不存在,创建它然后写入它但是,如果确实存在,只需访问它并写入其中的数据。

感谢任何形式的帮助

由于

1 个答案:

答案 0 :(得分:1)

创建新的Excel .xls文件:

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//..
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FuSsA sheet");
//Create a new row in current sheet
Row row = sheet.createRow(0);
//Create a new cell in current row
Cell cell = row.createCell(0);
//Set value to new value
cell.setCellValue("Slim Shady");
    try {
        FileOutputStream out = 
                new FileOutputStream(new File("C:\\new.xls"));
        workbook.write(out);
        out.close();
        System.out.println("Excel written successfully..");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

更新现有Excel文件(.xls.xlsx

try {
            File file = new File"C:\\update.xls");
            Workbook workbook = WorkbookFactory.create(file);
            Sheet sheet = workbook.getSheetAt(0);
            Cell cell = null;

            //Update the value of cell
            cell = sheet.getRow(1).getCell(2);
            cell.setCellValue(cell.getNumericCellValue() * 2);
            cell = sheet.getRow(2).getCell(2);
            cell.setCellValue(cell.getNumericCellValue() * 2);
            cell = sheet.getRow(3).getCell(2);
            cell.setCellValue(cell.getNumericCellValue() * 2);

            file.close();

            FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
            workbook.write(outFile);
            outFile.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

有关详细信息,请查看此问题:Read / Write different Microsoft Office file formats using Apache POI