1

我有一个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);            
}
4

2 回答 2

3

在当前行中创建 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);
    }
}
于 2013-04-23T23:44:37.657 回答
0
int rownum = 0;
int colnum = 0;
int itemsPerRow = 20;
String outfilename = "test.xls";
List<String> values = new ArrayList<String>();
// add some values ...

HSSFWorkbook book = new HSSFWorkbook();

HSSFSheet sheet = book.createSheet(

HSSFRow row = sheet.getRow(rownuw);

for(String s : values) {

   HSSFCell cell = row.createCell(colnum);
   cell.setCellValue(Integer.parseInt(id));
   colnum = (column+1)%itemsPerRow;
   if(colnum == 0) {
       rownum++;
       row = sheet.getRow(rownuw);
   }   
}

File f = new File("src/main/resources/films.xls");
FileOutputStream fos = new FileOutputStream(f);

book.write(fos);
fos.flush();
fos.close();
于 2013-04-23T23:30:32.483 回答