0

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 :)

hsemarap
  • 227
  • 3
  • 15

2 Answers2

4

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();
hsemarap
  • 227
  • 3
  • 15
  • Hi @hsemarap i am using your answer but it's not working I am getting error on this line `WritableWorkbook copy = Workbook.createWorkbook(new File("temp.xls"), workbook);` ERROR is `java.io.FileNotFoundException: temp.xls: open failed: EROFS (Read-only file system)` – Pushpendra Sep 15 '16 at 06:41
  • 1
    @APKAPPS It seems like you were trying to open a **Read-only file**. So, you'll probably need to get root access or, copying the file to a path which is not read-only and then you'll be able to make edit. – ʍѳђઽ૯ท Oct 04 '18 at 16:17
1

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.