POI Excel Read and Write corrupts the excel file

Hi,
I am using the below code:
public class ExcelUtils {

private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;

public static void setExcelFile(String Path,String SheetName) throws Exception
{

try {

// Open the Excel file

FileInputStream ExcelFile = new FileInputStream(Path);

// Access the required test data sheet

ExcelWBook = new XSSFWorkbook(ExcelFile);

ExcelWSheet = ExcelWBook.getSheet(SheetName);

}
catch (Exception e){

throw (e);

}

}

public static String getCellData(int RowNum,int ColNum) throws Exception
{

try
{

Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);

String CellData = Cell.getStringCellValue();

return CellData;

}
catch (Exception e)
{

return””;

}

}

@SuppressWarnings(“deprecation”)
public static void setCellData(String Result,  int RowNum, int ColNum) throws Exception    {

try{

Row  = ExcelWSheet.getRow(RowNum);

Cell = Row.getCell(ColNum,org.apache.poi.ss.usermodel.Row.RETURN_NULL_AND_BLANK );

if (Cell == null) {

Cell = Row.createCell(ColNum);

Cell.setCellValue(Result);

} else {

Cell.setCellValue(Result);

}

// Constant variables Test Data path and Test Data file name

FileOutputStream fileOut = new FileOutputStream(Constant.Path_TestData + Constant.File_TestData);

ExcelWBook.write(fileOut);

fileOut.flush();

fileOut.close();

}catch(Exception e){

throw (e);

}

}

}

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?

ankurgupta08 Default Asked on October 18, 2016 in Selenium WebDriver.
Add Comment
1 Answer(s)

Yes, the solution is to save the results in a different (new) file.

public static void saveFile(String filename){
// Constant variables Test Data path and Test Data file name
System.out.println(“Saving results in ” + filename) ;

try{
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
}
catch (Exception e){
System.out.println(“Error in saving results in : ” + filename);
}

}

sskini76 Train Answered on October 24, 2016.
Add Comment

Your Answer

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