How to Edit/Modify an existing Excel file in Java with Jexcel API

别说谁变了你拦得住时间么 提交于 2019-12-10 12:18:33

问题


I want to edit an existing Excel file with Java, to add some more data to an existing template excel file. So i used Jexcel for this purpose.

As suggested everywhere, I tried the following,

Workbook existingWorkbook = Workbook.getWorkbook(new File("H://"+file_name));
WritableWorkbook copy = Workbook.createWorkbook(new File("H://"+file_name+"_temp1.xls"));

But it shows an exception in the second line.

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>

So how could one edit an already existing jexcel file. I did get another warning

Warning: Text Object on sheet "sheet2" not supported - omitting

Thanks in advance :)


回答1:


Figured out the problem.

We have to close the input file before writing back (editing) the same file.

so to edit an existing Excel file with Jexcel

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();



回答2:


I ran into this same issue and to solve the problem I updated to the latest version of jxl.jar via maven. After doing this there was a very long delay when it ran destinationWorkbook = Workbook.createWorkbook(outputFile, sourceWorkbook); but it completed successfully without errors.



来源:https://stackoverflow.com/questions/24260354/how-to-edit-modify-an-existing-excel-file-in-java-with-jexcel-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!