Excel Format - .xls
I am trying to copy/Paste the values from one Excel sheet to another existing Excel sheet. I am unable to write values in empty rows. If the Excel rows have some values, then it is updating. Please check the code below.
My code:
FileInputStream file = new FileInputStream(new File(strWorkBookName));
HSSFWorkbook strWorkBook = new HSSFWorkbook(file);
HSSFSheet sheet = strWorkBook.getSheet(sheetName);
// Retrieve the row and check for null
HSSFRow sheetrow = sheet.getRow(rowNo);
if(sheetrow == null){
logger.info("CREATING ROW"+rowNo);
sheetrow = sheet.createRow(rowNo);
}
// Update the value of a cell
HSSFCell cell = sheetrow.getCell(columnNo);
if(cell == null){
logger.info("CREATING COLUMN " + columnNo);
cell = sheetrow.createCell(columnNo); }
cell.setCellValue(valueToUpdate);
FileOutputStream outFile = new FileOutputStream(new File(strWorkBookName));
strWorkBook.write(outFile);
outFile.close();
Are you sure you're verifying properly if the existing Excel file is updating?
You forgot to close the
Workbook
object, but still your code is working like a charm for me. Here is the working code I've tested (working both for full and empty rows):