POI Excel Write corrupts the excel file

Hi:

I’m reading the excel file <name>.xlsx  by below commands

public static XSSFWorkbook ExcelWBook;
public static XSSFSheet ExcelWSheet;
public static XSSFRow ExcelWRow;
public static XSSFCell ExcelCell;
FileInputStream sFile = new FileInputStream(sFilePath);

ExcelWBook = new XSSFWorkbook(sFile);

ExcelWSheet = ExcelWBook.getSheet(sSheetName);

System.out.println(“File OPened:” + sFile);

And Writing using

FileOutputStream sOutFile = new FileOutputStream(sFilePath);
ExcelUtils.ExcelWSheet= ExcelUtils.ExcelWBook.getSheet(“Sheet2”);
fWriteCellData(iXlRowNo,1,sActName);
fWriteCellData(iXlRowNo,2,sActDOB);

ExcelUtils.ExcelWBook.write(sOutFile);
sOutFile.flush();
sOutFile.close();

It reads all the values successfully, but writing into the excel file makes loss of all the existing data in the excel sheet. Opening the excel file returns the error message as “Excel cannot open the file “<filename.xlsx> because the file format or file extension is not valid.Verify the file has not been corrupted and the file extension matches the format of the file.

Any idea why this is happening?

Thanks,
Sudhakar

Add Comment
  • 1 Answer(s)

    For some reason if the for loop last row is less than the row count , script skips executing the below code. It had executed createcell and setcellvalue but skipped FileOutputstream Write, flush and close. When these statements skipped .xls file gets corrupted. Now, it’s resolved.

    ExcelUtils.ExcelCell=ExcelUtils.ExcelWRow.createCell(iColNo);
    ExcelUtils.ExcelCell.setCellValue(sActValue);

    ExcelUtils.ExcelWBook.write(sOutFile);
    sOutFile.flush();
    sOutFile.close();

    Train Answered on June 13, 2016.
    Add Comment
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.