当前位置: 首页 > 知识库问答 >
问题:

使用Apache POI编辑Excel文件时出错

从烈
2023-03-14

我正在尝试使用Apache POI编辑包含数据的excel文件。我编写了以下代码:

    FileInputStream fileInputStream = new FileInputStream(new File("file.xlsx"));
    Workbook workbook = WorkbookFactory.create(fileInputStream);
    Sheet sheet = workbook.getSheet("sheet");

    Row row = sheet.getRow(1);
    Cell cell = (row.getCell(1) == null) ? row.createCell(1) : row.getCell(1);
    cell.setCellType(CellType.STRING);
    cell.setCellValue("something here");.
    fileInputStream.close();

    try(FileOutputStream fileOut = new FileOutputStream("file.xlsx")) {
        workbook.write(fileOut);
        workbook.close();
    }

当我运行代码时,当我尝试打开Excel文件时,会出现以下错误:“我们发现‘file.xlsx’中的某些内容有问题。您希望我们尽可能多地恢复吗?如果您信任此工作簿的来源,请单击是。”

如果我单击是,Excel确实会使用我指定的值进行更新;但是,我不希望出现此错误。我如何解决这个问题?

共有1个答案

金晗日
2023-03-14

我试图创建一个类似的情况,但无法让它与资源的< code>try一起工作。但是,下面的代码显示了使用同一工作簿的读写序列。看看评论吧。

public static void main(String[] args) {
    /*
     * Setup:
     * An existing xlsx file with a first sheet containing 6 columns and 1 row.
     * The row has 6 filled cells with the values
     * cell 1 (index 0): There
     * cell 2 (index 1): is
     * cell 3 (index 2): a
     * cell 4 (index 3): house
     * cell 5 (index 4): in
     * cell 6 (index 5): New Orleans
     * 
     * Task:
     * Write the words "they", "call", "it", "the", "rising", "sun"
     * in the cells below.
     */

    // define the (correct) path to the workbook
    String pathToFile = "U:\\temp\\TestFiles\\Test-Workbook.xlsx";
    // create a Path object
    Path filePath = Paths.get(pathToFile);
    // declare a workbook
    XSSFWorkbook workbook;

    try {

        /*
         * READING from the .xlsx file:
         */
        FileInputStream in = new FileInputStream(filePath.toFile());
        workbook = XSSFWorkbookFactory.createWorkbook(in);
        XSSFSheet sheet = workbook.getSheetAt(0);

        // read all the cells of the first row and print their content
        for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
            XSSFRow row = sheet.getRow(i);
            for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
                XSSFCell cell = row.getCell(j);
                System.out.println(cell.getStringCellValue());
            }
        }

        /*
         * WRITING to the .xlsx file already read
         */

        // create some meaningful words to be added to some cells in the workbook
        List<String> wordsToBeWritten
                = Arrays.asList("they", "call", "it", "the", "rising", "sun");

        FileOutputStream out = new FileOutputStream(filePath.toAbsolutePath().toString());
        sheet = workbook.getSheetAt(0);
        XSSFRow row = sheet.createRow(sheet.getPhysicalNumberOfRows());
        // create new cells and write the words into them
        for (int i = 0; i < wordsToBeWritten.size(); i++) {
            XSSFCell cell = row.createCell(i);
            cell.setCellValue(wordsToBeWritten.get(i));
        }
        // close the FileInputStream
        in.close();
        // write the workbook using the FileOutputStream
        workbook.write(out);
        // force the FileOutputStream to write everything until it is empty
        out.flush();
        // close the FileOutputStream
        out.close();
        // close the workbook.
        workbook.close();
    } catch (FileNotFoundException e) {
        System.err.println("The file \"" + filePath.toAbsolutePath().toString() 
                + "\" could not be found.");
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Error while reading the file \"" 
                + filePath.toAbsolutePath().toString() + "\"");
        e.printStackTrace();
    } catch (InvalidFormatException e) {
        System.out.println("The file \"" + filePath.toAbsolutePath().toString() 
                + "\" has an invalid format(ting)");
        e.printStackTrace();
    } catch (EmptyFileException e) {
        System.err.println("The supplied file \"" 
                + filePath.toAbsolutePath().toString() + "\" is empty.");
        e.printStackTrace();
    }
}

编辑

我为此使用的唯一依赖项是poi-ooxml的4.0.0版本:

<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>4.0.0</version>
    </dependency>
</dependencies>
 类似资料:
  • 用户可以将Excel文档保存为. xls或xml-table。结果是一个具有固定结构的xml-file,Excel可以用它纠正工作。 可以用java中的ApachePOI打开这种类型的excel文件吗? 事先谢谢你,安德烈。

  • 我在运行时使用Java辅助编辑类,(添加一个新的构造函数) 不幸的是,这会抛出一个, 线程"main"javaid中的异常。Cannot CompileExcema: byjava.lang.IllegalAccessError: classjavax.swing.JFrame无法访问其超接口javax.swing.TransferHandler$HasGetTransferHandler at

  • 我试图修改一个excel文件,但由于某种原因,我不理解cell.SetCellValue方法在我的代码中不起作用。我实际上正在做的是:-我正在打开一个excel文件,并将感兴趣的内容保存在一个HashMap中。这样工作,我可以打印HashMap的内容。-然后,我试图用保存在HashMap中的数据修改另一个excel文件,但由于某种原因,这没有发生。 请帮忙,谢谢!

  • 我需要做以下工作 1) 复制一个巨大的excel文件1400*1400并复制一份。 2)读取复制的文件并添加新的列和行,并同时进行编辑。 3) 这将是一个独立的程序,而不是在服务器上。我有低内存占用和快速性能的限制。 我做了一些阅读,发现以下内容 1)没有 API 可以复制一个巨大的文件 2)SXSSF可以用于写,但不能用于读 3)XSSF和SAX(事件API)可以用于读取,但不能用于editin

  • vi 可以在命令行下编辑文件。 vi 要编辑的文件路径 练习:编辑文件 vi ninghao-project/README.md 这样会打开要编辑的文件,使用方向键可以移动光标。 编辑 想要编辑按一下小 i ,这样会进入到 vi 编辑器的编辑模式。这时你可以编辑文件里的内容,修改完成以后,按 esc 可以退出编辑模式。 搜索 搜索文件里的内容可以按 / ,然后输入要搜索的关键词,n 继续查找,

  • 我正在写一个程序,它需要从excel文件中读取和写入数据,而不考虑格式(xls或xlsx)。 我知道ApachePOI,但它似乎有不同的类来处理xls文件(HSSF)和xlsx(XSSF)文件。 任何人都知道我将如何实现我在这里的目标。(也欢迎使用POI以外的API的想法)。