gpt4 book ai didi

java - 在 apache poi 中每 10 个项目后插入新行

转载 作者:行者123 更新时间:2023-11-29 05:44:54 25 4
gpt4 key购买 nike

我有一个 List<String>它的元素很少,我想使用 Apache POI 将这些元素写入 Excel 工作表。我还想在每 10 个项目之后将数据放入单独的行中。例如,我的列表包含以下元素:

["aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","jjj","kkk","lll","mmm","nnn","ooo","ppp","qqq","rrr","sss","ttt",....]

我想在 excel 表中使用以下格式

        col1, col2, col3, col4, col5, col6, col7, col8, col9, col10
row1 : aaa, bbb, ccc, ddd, eee, fff, ggg, hhh, iii, jjj
row2 : kkk, lll, mmm, nnn, ooo, ppp, qqq, rrr, sss, ttt

这可以通过 Apache POI 实现吗?

我已经尝试了以下(我在循环中真的很糟糕)

public void csvUpdateWorksheet1(String fileName, String sheetName, List<String> data) {

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(sheetName);

logger.info(data.size());
int rownum = 0;
for (int i = 0; i < data.size(); i++) {
Row row = sheet.createRow(i);
Cell cell = row.createCell(i);
cell.setCellValue(data.get(i));
}
csvWriteToFile(workbook, fileName);
}

最佳答案

在当前行中创建 10 个单元格后,您将需要创建下一行。

int r = 0;
int c = 0;
int maxCellsPerRow = 10;
Row row = sheet.createRow(r);
for (String str : data)
{
Cell cell = row.createCell(c);
cell.setCellValue(str);

c++;
// Create and advance to next row if needed.
if (c >= maxCellsPerRow)
{
c = 0;
r++;
row = sheet.createRow(r);
}
}

关于java - 在 apache poi 中每 10 个项目后插入新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16180756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com