我想用Java编辑现有的Excel文件,以便向现有的模板excel文件添加更多数据。所以我为此目的使用了Jexcel。
正如各地建议的那样,我尝试了以下内容,
Workbook existingWorkbook = Workbook.getWorkbook(new File("H://"+file_name));
WritableWorkbook copy = Workbook.createWorkbook(new File("H://"+file_name+"_temp1.xls"));
但它在第二行显示异常。
jxl.common.AssertionFailed
at jxl.common.Assert.verify(Assert.java:37)
at jxl.read.biff.SheetReader.handleObjectRecord(SheetReader.java:1811)
at jxl.read.biff.SheetReader.read(SheetReader.java:1059)
at jxl.read.biff.SheetImpl.readSheet(SheetImpl.java:716)
at jxl.read.biff.WorkbookParser.getSheet(WorkbookParser.java:257)
at jxl.write.biff.WritableWorkbookImpl.copyWorkbook(WritableWorkbookImpl.java:969)
at jxl.write.biff.WritableWorkbookImpl.<init>(WritableWorkbookImpl.java:343)
at jxl.Workbook.createWorkbook(Workbook.java:339)
at jxl.Workbook.createWorkbook(Workbook.java:320)
at run_book.process_input.<init>(process_input.java:83) <--create workbook stt.
.........<stack trace goes on>
那么如何编辑已经存在的jexcel文件呢? 我确实得到了另一个警告
警告:工作表上的文字对象&#34; sheet2&#34;不支持 - 省略
提前致谢:)
答案 0 :(得分:4)
找出问题所在。
在写回(编辑)同一文件之前,我们必须关闭输入文件。
所以用Jexcel编辑现有的Excel文件
File inp = new File("H://"+file_name);
File out = new File("H://"+file_name);
Workbook existingWorkbook = Workbook.getWorkbook(inp);// This opens up a read-only copy of the workbook
WritableWorkbook copy = Workbook.createWorkbook(out,existingWorkbook); // This opens up a writable workbook so that we can edit the copy
//..........Some writes to excel workbook...........
// Now before writing & closing the copy, first close the existing one
existingWorkbook.close(); // Important: Close it before writing the copy with copy.write();
inp.close();
copy.write();
copy.close();
答案 1 :(得分:0)
我遇到了同样的问题并解决了我通过maven更新到最新版本的jxl.jar的问题。执行此操作后,运行destinationWorkbook = Workbook.createWorkbook(outputFile, sourceWorkbook);
时出现了很长时间的延迟,但成功完成且没有错误。