java - 它写入列表的第一条记录或最后一条记录,任何正确的建议

标签 java arraylist

我在将数据写入 Excel 工作表时遇到问题。我的程序的另一部分将生成对象的 ArrayList 并将其发送到此循环。此循环一个接一个地读取对象并写入 Excel 工作表。

我知道我错过了什么。它只写入列表中的最后一个对象。

如果我尝试将这段代码放在 while 循环中:

FileOutputStream out = new FileOutputStream(writeExcel);
        writeExtraBook.write(out);
        out.close();

然后它只将第一条记录写入文件。

谁能帮我解决我做错的地方

这是写入数据的代码:

String writeExcel = CONSTANTS.FOW_FILE_PATH;

    FileInputStream writeInput;
    try {
        writeInput = new FileInputStream(writeExcel);

        /** Create a POIFSFileSystem object **/
        POIFSFileSystem mywriteSystem = new POIFSFileSystem(writeInput);
        HSSFWorkbook writeExtraBook = new HSSFWorkbook(mywriteSystem);
        HSSFSheet myExtrasSheet = writeExtraBook.getSheet("FOW");
        HSSFRow extraRow = null;
        HSSFCell extraRowCell = null;
        int lastRowNumber = myExtrasSheet.getLastRowNum();

        Iterator<FoWForm> iter = fowList.iterator();
        while (iter.hasNext()) {
            extraRow = myExtrasSheet.createRow(lastRowNumber + 1);
            FoWForm form = iter.next();
            extraRowCell = extraRow.createCell(0);
            extraRowCell.setCellValue(lastRowNumber + 1);
            extraRowCell = extraRow.createCell(1);
            extraRowCell.setCellValue(form.getFowDesc());
            extraRowCell = extraRow.createCell(2);
            extraRowCell.setCellValue(form.getForCountry());
            extraRowCell = extraRow.createCell(3);
            extraRowCell.setCellValue(form.getMatchId());
            extraRowCell = extraRow.createCell(4);
            extraRowCell.setCellValue(form.getAgainstCountry());

        }
        FileOutputStream out = new FileOutputStream(writeExcel);
        writeExtraBook.write(out);
        out.close();
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

最佳答案

我怀疑这是问题所在:

int lastRowNumber = myExtrasSheet.getLastRowNum();
...
while (iter.hasNext()) {
    extraRow = myExtrasSheet.createRow(lastRowNumber + 1);

您只评估一次 lastRowNumber - 因此在每次迭代中,您都使用相同的新行号调用 createRow,这可能会覆盖该行。

我怀疑你想要:

lastRowNumber++;

在循环中...

关于java - 它写入列表的第一条记录或最后一条记录,任何正确的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9766320/

相关文章:

java - Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - 相当于 IN 子句

java - 对带有字符串前缀的数组进行二分搜索

java - 面板背景图片截图

java - 在其他物体前面 Swing 物体

java - 如何在 FileOutputStream 中使用数组列表

java - 将某些子字符串前缀添加到数组列表中

Java 错误的主要版本

java - 获取两个 arrayList 之间的差异,但以大写形式比较它们

Java - 具有递归方法和嵌套迭代器的 ConcurrentModificationException

javascript - 返回一个与数组中当前数字不同的新数字