Reputation: 1
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();
Upvotes: 0
Views: 905
Reputation: 428
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):
public static void main(String[] args) throws IOException {
int sheetPosition = 0;
int rowPosition = 100;
int cellPosition = 100;
String excelFilePath = "D:\\Desktop\\testExcel.xls";
FileInputStream fileInputStream = new FileInputStream(new File(excelFilePath));
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet sheet = workbook.getSheetAt(sheetPosition);
HSSFRow sheetrow = sheet.getRow(rowPosition);
if (sheetrow == null){
System.out.println("new row at position " + rowPosition);
sheetrow = sheet.createRow(rowPosition);
}
HSSFCell cell = sheetrow.getCell(cellPosition);
if(cell == null){
System.out.println("new cell (for row " + rowPosition + ") at position " + cellPosition);
cell = sheetrow.createCell(cellPosition);
}
cell.setCellValue("New Amazing Value!");
FileOutputStream outFile = new FileOutputStream(new File(excelFilePath));
workbook.write(outFile);
outFile.close();
workbook.close(); // <-- Do not forget that!
}
Upvotes: 1