我的数据存储在 ArrayList 中,我想将该数据写入 Excel 工作簿中的多个工作表中。 我能够在 Excel 工作簿中写入数据,但它是在同一张表中写入的。 截至目前,我可以通过以下方式写入数据,如下图所示:
但是我想将数据分成多张表, 数据应该从标题中中断,即 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/