简体   繁体   中英

How to use same workbook to read and write into Excel file (.xlsx)?

Is it possible to use same workbook to read and write into an Excel file (.xlsx) ?

I try to use the same workbook to improve performance.

Indeed, opening, closing, opening, closing,... is not very efficient.

So I keep the workbook in a "global variable".

this.FileInputStream = null
this.Workbook = null

public void before() {
     this.FileInputStream = new FileInputStream (new File('File.xlsx'))
     this.Workbook = new XSSFWorkbook(this.FileInputStream)
}

public void read() {
     XSSFSheet sheet = this.Workbook.getSheet(sheetName) 
     ...
}

public void write() {
     XSSFSheet sheet = this.Workbook.getSheet(sheetName) 
     ...
     FileOutputStream outFile = new FileOutputStream(new File('File.xlsx'))
     this.Workbook.write(outFile)
     outFile.close()
}    

public void after() {
     this.Workbook = null
     this.FileInputStream.close()
     this.FileInputStream = null 
}

Error

org.apache.xmlbeans.impl.values.XmlValueDisconnectedException

on line

this.Workbook.write(outFile)

Can you help me to improve this ?

Thank you in advance,

Regards,

Moving my answer from the comments:

I've found that there used to be a bug related to writing more than once: bz.apache.org/bugzilla/show_bug.cgi?id=49940 . It was probably fixed in the version 3.10-FINAL (2014-02-08).

If you are using the older version and can't get the newer one then your best bet probably would be not to write multiple times to the same workbook. Either do all the changes at once after opening it and write once or reopen the file after each write.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM