Apache POI:克隆包含图表的工作表 [英] Apache POI: cloning worksheets containing charts

查看:61
本文介绍了Apache POI:克隆包含图表的工作表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据众多消息来源,例如 官方页面上的限制部分,可能是从 POI 使用 Excel 图表的唯一好方法是使用 Excel 文件和现有图表作为模板并修改图表使用的源单元格.而且效果很好.

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.

问题是,我们需要的不仅是一张,而是多张(在编译时我们不知道有多少)工作表,它们具有相同的图表但不同(动态生成的)数据.使用 cloneSheet(sheetNumber) 是一种复制模板工作表的方法.但如果工作正常,直到图表被克隆到工作表上.

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)

更新:

我切换到 XSSF,现在至少没有运行时异常.复制工作表数据但不复制图表(它们不存在于复制的工作表中).

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

是否有人成功克隆了带有图表的工作表?或者也许有人对如何解决我们遇到的问题有其他想法,即为带有 POI 的动态数量的工作表生成 excel 图表?

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?

推荐答案

我最终得到了相当复杂的解决方法:

I ended up with quite complex workaround:

  1. 我通过 Excel 宏使用模板图表生成了大量工作表(例如 1000 张)
  2. 我使用 Apache POI 将数据输入到任意数量的工作表中(并使用图表使用的命名范围进行操作)
  3. 我使用 Apache POI 将尽可能多的工作表重命名为我需要的名称(因此我仅限于 HSSF,因为 XSSF 在重命名工作表后不会更新 Excel 中的命名范围引用:-()
  4. 我用 Apache POI 删除了其余的工作表

实现这个概念上简单且常见的用例(即使用图表导出到 Excel)是一项艰巨的努力,但至少它是可能的,并且运行良好.

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.

这篇关于Apache POI:克隆包含图表的工作表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆