且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java的POI Excel中创建新列,新行

更新时间:2023-12-03 14:24:22

在你的循环,你在索引0&放重现行的每个迭代; 1.当您重新创建这些行,你会吹走所有已经存在的数据。

尝试是这样的:

 时int k = 1;
行myRow1 = sheet.createRow(0); //文档的第一行
行myRow2 = sheet.createRow(1);
对于(名单DataList控件:someList){
  myRow1.createCell(K).setCellValue(dataList.getVal()));
  myRow2.createCell(K).setCellValue(dataList.getSecVal()));
  ķ++;
}

Ok so Im iterating over a list and instead of inserting values into cells horizontally, im putting the values in the cells vertically.

It works fine for the first time through the list but when I go in the list the 2nd time it blows away the first list and replaces it in the 2nd column.

if i remove the row= 0 at the end of the loop, it look like:

val 1
val 2
      val 1
      val 2

=========

int row = 0;
int k = 1; 
for (List dataList: someList) {
  Row myRow = sheet.createRow ((short)row);

  myRow.createCell(k).setCellValue (dataList.getVal())); 
  myRow = sheet.createRow ((short)row++);

  myRow.createCell(k).setCellValue (dataList.getSecVal())); 
  myRow = sheet.createRow ((short)row++);
  k++;
  row = 0;
}

On each iteration of your loop, you're recreating the rows at index 0 & 1. When you re-create these rows, you're going to blow away all of your already existing data.

Try something like this:

int k = 1;
Row myRow1 = sheet.createRow(0); //first row of the document
Row myRow2 = sheet.createRow(1);
for (List dataList: someList) {
  myRow1.createCell(k).setCellValue (dataList.getVal())); 
  myRow2.createCell(k).setCellValue (dataList.getSecVal())); 
  k++;
}