I am interested and would like to learn more about java , how to write into existing excel sheets / manipulating the existing data. I was wondering if you could give me an idea on how to edit an existing excel file and save it using the jxl api / Apache POI or perhaps give me a sample program on how to edit some data in an existing excel file and then save it Thanks in advance !!
Asked
Active
Viewed 8.5k times
4 Answers
33
The tutorials here are very helpful and well-written. They use an external JAR developed by the Apache POI project. Here's an simple example of editing one cell:
InputStream inp = new FileInputStream("wb.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt([sheet index]);
Row row = sheet.getRow([row index]);
Cell cell = row.getCell([cell index]);
String cellContents = cell.getStringCellValue();
//Modify the cellContents here
// Write the output to a file
cell.setCellValue(cellContents);
FileOutputStream fileOut = new FileOutputStream("wb.xls");
wb.write(fileOut);
fileOut.close();
Hope it helps

Roy Dictus
- 32,551
- 8
- 60
- 76

Zabbala
- 2,183
- 1
- 17
- 17
-
At what point do you close the FileInputStream? If you try to read from it after the output stream is closed, will it reflect all of the changes? And, shouldn't the FileOutputStream be opened in append mode? – Edward Q. Bridges Jun 12 '12 at 15:48
-
@eqbridges As I found out the InputStream is closed by default in the constructor. (I know you comment is over a year old but may be it will help others) – das Keks Nov 11 '13 at 14:56
5
One very important tip that I learned the hard way. Open the OutputStream only after you have completed writing to your excel workbook. Zabbala's example is spot on and shows this correctly. If you open the OutputStream any earlier, your changes would not be written to the file after your program exits and you would be scratching your head as I did.

asarkar
- 51
- 1
- 1
3
I refresh the formulas with another tab for this I use the next sentence
HSSFSheet worksheetse = workbook.getSheetAt(0);
worksheetse.setForceFormulaRecalculation(true);
but it's necesary that you apply the method setForceFormulaRecalculation for all the tabs that have the formulas.
Sorry for my English
-
Note that `HSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);` may not work if the spreadsheet uses specific types of functions (with n arguments, which is not implemented in poi). However `worksheetse.setForceFormulaRecalculation(true);` seems to work in this case. – Vasilen Donchev Nov 08 '12 at 15:12
-
@VassilenDontchev Can you please give some examples to show in which cases `HSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);` will fail – SpringLearner Jun 23 '16 at 13:12