使用Java Apache POI更新Excel中的单元格值

时间:2016-12-16 07:58:39

标签: java excel apache apache-poi

我正在尝试使用Apache POI更新现有的Excel。

问题是,我有一个excel有第三列电话号码,我想使用if语句将它们更正为特定格式。

但是我无法写入文件。

以下是我正在使用的代码:

 public void readingExcel(String fileName) throws Exception {
    try (FileInputStream file = new FileInputStream(new File(fileName))) {
        HSSFWorkbook workbook = new HSSFWorkbook(file);
        HSSFSheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();
            int counter = 0;
        for (Row row : sheet) {
            int columnIndex = 2;
            row = CellUtil.getRow(counter, sheet);
            Cell cell = CellUtil.getCell(row, columnIndex);
            if (formatter.formatCellValue(cell).length() == 8)
                cell.setCellValue("+216" + formatter.formatCellValue(cell));
            if (formatter.formatCellValue(cell).length() == 11 && formatter.formatCellValue(cell).startsWith("216"))
                cell.setCellValue("+" + formatter.formatCellValue(cell));
            counter++;
        }

        FileOutputStream outFile =new FileOutputStream(new File(fileName));
        workbook.write(outFile);
        outFile.close();
    }  
}

我收到此错误

org.apache.poi.poifs.filesystem.NotOLE2FileException: Invalid header signature; read 0x0000000000000000, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:181)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:140)
at org.apache.poi.poifs.filesystem.NPOIFSFileSystem.<init>(NPOIFSFileSystem.java:302)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:398)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:379)
at excelapp.myClass.readingExcel(myClass.java:50)
at excelapp.myClass.<init>(myClass.java:41)
at excelapp.ExcelApp.main(ExcelApp.java:26)

事情是,它对今天来说非常重要,而且我真的很难更新该列的价值: - /任何人有想法?我想我写错了方法..

0 个答案:

没有答案