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?

2
  • 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. Commented Mar 21, 2021 at 6:29
  • And HSSFWorkbook 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. Commented Mar 21, 2021 at 6:33

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.