Im trying to write a function that writes into a excel file. The function will be called multiple times in a loop each loop writing something in a new row.
public static void ExcelImport (String SheetName, String NameExcel, String Oobj,Integer i )
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("SheetName");
//create Row
Row Row = sheet.createRow(i-1);
//create column
Cell Cell = Row.createCell(1);
//write
Cell.setCellValue(Oobj);
try
{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("C:\\Users\\Name\\Desktop\\" + NameExcel + ".xls"));
workbook.write(out);
out.close();
System.out.println(i);
}
catch (Exception e)
{
e.printStackTrace();
}
}
It is realy simple my goal is to write String Oobj into the second column for i rows. But for some reason it only writes the last run. For example if the loop made 6 runs then there will only be something written in column 2 row 5. Instead of having Oobj in row 0, "Oobj1" in row 1, "Oobj2" in row 2 etc. I just get "Oobj5" in row 5
Could it be because every time there is a new sheet created which overwrite the old one? in that case how would write in the same sheet?
HSSFWorkbook workbookobject would must be outside that method. It could be a class member for example. But then also the writing the workbook would must be outside of that method because theworkbookis closed after writing.createSheetbut also hasgetSheetmethods. So try to get the sheet at first and only create it new if it is not present already.