简体   繁体   中英

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. 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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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