0

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?

IVnoobSuck
  • 75
  • 10
  • 1
    "Could it be because every time there is a new sheet created which overwrite the old one?": Not only the sheet, even the workbook is new created every time. "how would write in the same sheet?": The `HSSFWorkbook workbook` object 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 the `workbook` is closed after writing. – Axel Richter Mar 21 '21 at 06:29
  • And [HSSFWorkbook](http://poi.apache.org/apidocs/dev/org/apache/poi/hssf/usermodel/HSSFWorkbook.html) not only has `createSheet` but also has `getSheet` methods. So try to get the sheet at first and only create it new if it is not present already. – Axel Richter Mar 21 '21 at 06:33

1 Answers1

1

"that writes into a excel file" is not clear.

In case of an .xlsx file: This is a zip container of some folder structure, where you can do anything, if you understand the structure.

In case you want to change contents of some opened Excel sheet: Have good experience with COM-adapter JACOB, see How to call an Excel VBA Macro from Java Code?

Sam Ginrich
  • 661
  • 6
  • 7