简体   繁体   English

如何使用jlx在Java的同一Excel工作表中写入数据循环?

[英]How to write loop of data in the same excel sheet in Java using jlx?

I have a code produce 10 results and I need to export these results in one column in Excel sheet. 我有一个代码会产生10个结果,我需要将这些结果导出到Excel工作表的一列中。 However, the code shows only the last result in the last 10th row. 但是,该代码仅显示最后第十行中的最后一个结果。

The cods is shown down where I need to get R[i] in the same column under "A label record" 编码显示在“标签记录”下同一列中需要获取R [i]的位置

import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class GetResults{
public static void main(String[] args) throws BiffException, IOException, WriteException{
  int [] R = {1,2,3,4,5,6,7,8,9,10};
  for(int i=0; i<10; i++){
  WritableWorkbook wworkbook;
  wworkbook = Workbook.createWorkbook(new File("output.xls"));
  WritableSheet wsheet = wworkbook.createSheet("First Sheet", 0);
  Label label = new Label(0, 2, "A label record");
  wsheet.addCell(label);
  Number number = new Number(0, 3+i, R[i]);
  wsheet.addCell(number);
  wworkbook.write();
  wworkbook.close();
  }
 }
}

You are repeatedly creating a new worksheet and overwriting the previous file with it. 您正在反复创建一个新的工作表并用它覆盖以前的文件。 As a result, only the results from the last loop iteration survives. 结果,只有最后一次循环迭代的结果得以保留。

Move the worksheet and file creation outside of the loop. 将工作表和文件创建移出循环。 Each loop iteration should only add cells to the same, single sheet. 每次循环迭代应仅将单元格添加到同一张单页纸上。

Proper indentation might have made this more obvious. 适当的缩进可能使这一点更加明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM