Java 使用 jxl api / Apache POI 编辑现有的 excel 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/521274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Edit existing excel files using jxl api / Apache POI
提问by
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 !!
我很感兴趣并想了解更多关于 java ,如何写入现有的 excel 表/操作现有数据。我想知道您是否可以给我一个关于如何编辑现有 excel 文件并使用 jxl api / Apache POI 保存它的想法,或者给我一个关于如何编辑现有 excel 文件中的一些数据然后保存它的示例程序提前致谢 !!
回答by Zabbala
The tutorials hereare 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:
这里的教程非常有帮助,而且写得很好。他们使用由 Apache POI 项目开发的外部 JAR。这是编辑一个单元格的简单示例:
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
希望能帮助到你
回答by Alex
Hello i have the same problem than neXGen. But strangely if i open the file with openoffice, it works!
您好,我有与 neXGen 相同的问题。但奇怪的是,如果我用 openoffice 打开文件,它就起作用了!
Edit: perhaps i found a solution, put this after changing the values:
编辑:也许我找到了一个解决方案,在更改值后放置它:
HSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);
回答by Edwin Pomayay Yaranga
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.
但有必要为所有具有公式的选项卡应用 setForceFormulaRecalculation 方法。
Sorry for my English
对不起我的英语不好
回答by asarkar
One very important tip that I learned the hard way. Open the OutputStream onlyafter 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.
我通过艰难的方式学到的一个非常重要的技巧。只有在完成写入 Excel 工作簿后才打开 OutputStream 。Zabbala 的示例恰到好处并正确显示了这一点。如果您更早地打开 OutputStream,您的更改将不会在您的程序退出后写入文件,您会像我一样摸不着头脑。