如何更新 java 中的 excel 文件?

How to update an excel file in java?

我需要检查 excel 文件中的 30 sheets。每个 sheet 最多有 7 行和大量列。

我需要通过在最后一个现有列之后添加 32 个新列来更新每一行(如果某个条件为真),然后保存文件。

所以我需要能够从同一段代码对我的 excel 文件进行读取和写入,然后保存更新原始 excel 文件的更改(使用相同的文件名).

我真的认为 Apache Poi is the best solution when it comes to managing excels in Java. You might want to have a look at these examples provided by Apache Poi itself about this topic (the url may change slightly over time). This article 也可以为您要求的解决方案提供提示。

您可以使用 WorkbookFactory 创建一个新的 Workbook(代表您的 excel 的 Java 对象),如下所示:

Workbook workbook = WorkbookFactory.create(new FileInputStream(excelFilePath));

其中 excelFilePath 是(显然)您要更新的 excel 文件的路径。

您现在可以用 Workbook 做任何您想做的事了,欢呼!您既可以阅读和更改其所有内容,也可以(最终)编写新内容! 请注意,对 Workbook 的所有更改实际上不会影响您的 excel 文件。 您正在编辑 Workbook Java 对象,而不是实际的 excel 文件。从某种意义上说,你的Workbook最初是根据你的excel文件内容创建的,然后就完全独立于它了。

编辑完 Workbook 后,您可以将其保存以覆盖初始 excel 文件(在某种程度上,您现在正在更新 excel 包含所有更改的文件) 如下:

FileOutputStream outputStream = new FileOutputStream(excelFilePath);
workbook.write(outputStream);
workbook.close();
outputStream.close();

大功告成!简单有效!

这是一些可能适合您需要的代码:

public static void main(String[] args) throws EncryptedDocumentException, IOException {
    
    // Step 1: load your excel file as a Workbook
    
    String excelFilePath = "D:\Desktop\testExcel.xlsx";
    Workbook workbook = WorkbookFactory.create(new FileInputStream(excelFilePath));
    
    // Step 2: modify your Workbook as you prefer
    
    Iterator<Sheet> sheetIterator = workbook.sheetIterator(); // Getting an iterator for all the sheets
    while (sheetIterator.hasNext()) {
        Iterator<Row> rowIterator = sheetIterator.next().rowIterator(); // Getting an iterator for all the rows (of current sheet)
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            // Put here your internal logic to understand if the row needs some changes!
            int cellsn = row.getLastCellNum() == -1 ? 0 : row.getLastCellNum();
            for (int j = cellsn ; j < cellsn + 32 ; ++j) {
                row.createCell(j, CellType.STRING).setCellValue("New column after the last existing one n°" + (j - cellsn + 1));
            }
        }
    }
    
    // Step 3: update the original excel file with all your amazing changes!
    
    FileOutputStream outputStream = new FileOutputStream(excelFilePath);
    workbook.write(outputStream);
    workbook.close();
    outputStream.close();
}

一些最后的说明:

不要调用方法 create(java.io.File file) instead of create(java.io.InputStream inp) while using WorkbookFactory and creating your Workbook, it will lead to problems when saving your file as it's discussed on this post

我真的不知道你最初将标签“selenium”添加到你的问题的原因但是如果你想使用一些蜘蛛代码来“手动" 打开并编辑您的 excel 文件,请不要。这个解决方案和 HSSF 一样可怕(你得到 joke 了吗?)。

如果您使用的是 .xlsx excel 文件,您可能需要使用 Apache Poi XSSF 对象(如 XSSFWorkbook, XSSFRow and XSSFCell). More about .

最后,这里是我的代码 运行 所需的所有库的明确列表(它们很多,不要惊慌):Apache Poi 4.1.2, Apache Poi Ooxml 4.1.2, Apache Poi Ooxml Schemas 4.1.2, XmlBeans, Commons Codec, Commons Collections4, Commons Compress and Commons Math3。如果您使用的是 Maven,只需将以下行添加到您的依赖项文件中:

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi</artifactId>
   <version>4.1.2</version>
</dependency>

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>4.1.2</version>
</dependency>

仅此而已,希望对您有所帮助!干得好!