這不是一個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(每行單元數)的原因。
你如何在代碼中創建'sheet'? – user7291698
我懷疑你從互聯網上拿了一些代碼,並試圖使它適應你的需求。最好的做法是仔細檢查這些代碼,瞭解每個調用,並檢查Apache POI文檔中的確切內容以及API提供的其他可能性。這將爲您提供創建滿足您個人需求的程序所需的知識。 – RealSkeptic
@ user7291698: - 我按以下方式創建工作表: 第一次循環之前 工作表= wb.createSheet(「ExpectedResults」); –