问题
According to numerous sources, for example Limitations section on official page, probably the only good way to work with excel charts from POI is using Excel file with existing chart as a template and modify source cells used by chart. And it works great.
The problem is that we need to have not only one but multiple (and we don't know how many at compile time) worksheets with the same chart but different (dynamically generated) data. Using cloneSheet(sheetNumber) is a way to duplicate a template worksheet. But if works fine only until charts are on sheet being cloned.
When I try to clone a sheet with a chart I'm getting:
Exception in thread "main" java.lang.RuntimeException: The class org.apache.poi.hssf.record.chart.ChartFRTInfoRecord needs to define a clone method
at org.apache.poi.hssf.record.Record.clone(Record.java:71)
at org.apache.poi.hssf.model.InternalSheet.cloneSheet(InternalSheet.java:388)
at org.apache.poi.hssf.usermodel.HSSFSheet.cloneSheet(HSSFSheet.java:125)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.cloneSheet(HSSFWorkbook.java:652)
UPDATE:
I switched to XSSF and now at least there is no runtime exception. Sheet data is cloned but not charts (they are not present in cloned sheet).
Did anyone succeed to clone a worksheet with chart(s)? Or maybe someone has other idea how to solve a problem that we have, i.e. generating excel charts for dynamic number of worksheets with POI?
回答1:
I ended up with quite complex workaround:
- I generate big number of sheets (for example 1000) with template chart by Excel macro
- I enter data to as many sheets as I need with Apache POI ( and manipulate with named ranges that are used by charts)
- I rename as many sheets as I need with Apache POI to names that I need (and hence I'm limited to HSSF, because XSSF doesn't update named ranges references in Excel after renaming sheet :-( )
- I delete the rest of sheets with Apache POI
It was a serious effort to implement this conceptually simple and common use case (i.e. exporting to Excel with charts) but at least it's possible and it's working quite well.
来源:https://stackoverflow.com/questions/9686891/apache-poi-cloning-worksheets-containing-charts