java - poi无法将数据写入.xlsx

标签 java excel apache-poi

问题是当我尝试将数据写入单元格时,单元格要么尚未创建,要么只是不显示其中的数据。

例如,

Row[] rownames = new Row[names.size()];
for(int i = 0; i < names.size(); i++){
    rownames[i] = sheet.createRow(i+3);
    Cell machine = rownames[i].createCell(0);
    machine.setCellType(Cell.CELL_TYPE_STRING);
    machine.setCellValue(names.get(i).toString());
}

names[] 是一个包含名称列表的数组。

Cell machine = rownames[i].createCell(0); 在 (i+3,0) 处创建一个单元,其中 i 表示行。

machine.setCellValue(names.get(i).toString()); 将单元格值设置为相应的 name[i]。

我尝试了 print names[]machine.getStringCellValue(),它们都可以返回完全正确的数据(例如输出到控制台)。但 xlsx 文件中没有任何内容。非常感谢。

编辑: 让我解释得更清楚一些,所以如果一切顺利的话,这个 xlsx 文件的具体部分应该是这样的:

哈利| (第 3 行,第 0 列) 凯特| (第 4 行,第 0 列) 吉姆 | (第 5 行,第 0 列) 亚伦 | (第 6 行,第 0 列) ... ...

但现在的情况是:

| (第 3 行,第 0 列) | (第 4 行,第 0 列) | (第 5 行,第 0 列) | (第 6 行,第 0 列) ... ... 现在 xlsx 是 4KB。它包含一些其他信息,这些信息是通过这个程序放置在那里的。这些部分不存在这个问题。

最佳答案

看起来您在进一步的(未发布的)代码中多次按相同索引创建行。

poi 如何创建 XSSFRow:

public XSSFRow createRow(int rownum) {
    CTRow ctRow;
    XSSFRow prev = _rows.get(rownum);
    if(prev != null){
        // the Cells in an existing row are invalidated on-purpose, in order to clean up correctly, we
        // need to call the remove, so things like ArrayFormulas and CalculationChain updates are done 
        // correctly. 
        // We remove the cell this way as the internal cell-list is changed by the remove call and 
        // thus would cause ConcurrentModificationException otherwise
        while(prev.getFirstCellNum() != -1) {
            prev.removeCell(prev.getCell(prev.getFirstCellNum()));
        }

        ctRow = prev.getCTRow();
        ctRow.set(CTRow.Factory.newInstance());
    }
    ...
}

因此,如果行存在并且包含单元格,则所有包含数据的单元格都将被删除。

要避免这种情况,请使用 CellUtil 类:

  • Get a row from the spreadsheet, and create it if it doesn't exist.

    CellUtil.getRow(rowIndex, sheet);
    
  • Get a specific cell from a row. If the cell doesn't exist, then create it.

    CellUtil.getCell(row, columnIndex);
    

关于java - poi无法将数据写入.xlsx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34347089/

相关文章:

java - 取整数数组

java - Heroku Java 应用程序在本地崩溃但在网络上没有

JavaScript 重定向 URL

java - 使用 nginx/Tomcat7 和 Java 应用程序保护单个文件

vba - 使用 VBA 的 Excel 图表的主题图表样式

c# - 如何使用 IDisposable 接口(interface)释放 excel 对象

apache-poi - Apache Poi 默认时区

html - 添加将 html 转换为 msword 文档的功能

java - 如何在 Jersey/Spring 中使用 @QueryParam 重载方法?

java - Apache POI XSLF 创建部分