java - 如何将arrayList中的数据写入多个excel表格

标签 java apache-poi

我的数据存储在 ArrayList 中,我想将该数据写入 Excel 工作簿中的多个工作表中。 我能够在 Excel 工作簿中写入数据,但它是在同一张表中写入的。 截至目前,我可以通过以下方式写入数据,如下图所示:

enter image description here

但是我想将数据分成多张表, 数据应该从标题中中断,即 S.NO、Col1...Col6,当出现这种情况时,数据应该写入新工作表。

我正在使用此代码将数据写入 Excel

for (int i = 0; i < listOfResults.size(); i++) {
            row = sheet.createRow(i);
            for (int j = 0; j < 7; j++) {
                cell = row.createCell(j);
                if (j + add < listOfResults.size()) {
                    cell.setCellValue(listOfResults.get(j + add));

                }
            }

            add += 7;
        }

请帮忙..

最佳答案

这与其说是 POI 问题,不如说是中断逻辑问题。

您的代码

for (int i = 0; i < listOfResults.size(); i++) {
    row = sheet.createRow(i);
    for (int j = 0; j < 7; j++) {
        cell = row.createCell(j);
        if (j + add < listOfResults.size()) {
            cell.setCellValue(listOfResults.get(j + add));
        }
    }
    add += 7;
}

此处没有任何内容可检测标题行,因此您不会创建新工作表。您需要检测中断,然后创建一个新工作表,并将每个标题的行索引重置为零。

修改后的代码

int rowIndex = 0;
int firstCellInRow = 0;
int cellCount = listOfResults.size();
int cellsPerRow = 7;
int rowCount = cellCount / cellsPerRow;

for (int i = 0; i < rowCount; i++) {

    // detect first header cell
    firstCellInRow = i * cellsPerRow;
    if (listOfResults.get(firstCellInRow).equals("S.NO")) {
        // create a new sheet
        sheet = wb.createSheet();
        // reset the row index to 0
        rowIndex = 0;
    }

    // create the row and increment the row index
    row = sheet.createRow(rowIndex++);

    // now add the data to the cells
    for (int j = 0; j < cellsPerRow; j++) {
        cell = row.createCell(j);
        if (firstCellInRow + j < listOfResults.size()) {
            cell.setCellValue(listOfResults.get(firstCellInRow + j));
        }
    }
}

另一个问题是您运行主循环的次数过多。您要为每个单元格循环一次,但您确实想每行循环一次。这就是在第一个循环中将列表长度(单元格数)除以 7(每行单元格数)的原因。

关于java - 如何将arrayList中的数据写入多个excel表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42454276/

相关文章:

java - 如何在 Eclipse 中使用条件断点?

java - 如何使用 jBCrypt 比较来自 2 个 servlet 的散列密码

java - save方法中的entityName参数是什么?

java - 从 Android 中的两个不同 Activity 打开时 Activity 的不同行为

java - 使用 Apache POI 获取 .xlsx 文件中图像的图像位置/位置

java - 正确停止 Tika 服务器

java - 使用 HSSFSheet 将列格式类型设置为日期或时间

java - Apache POI Excel 工作表 : resize a picture while keeping its ratio

java - 对于Apache poi折线图,如何使第一列不显示在y轴上

java - 如何使用excel或其他方法修改测试参数?