如何将JasperReport导出为具有多个工作表的Excel文件?

17

我们有一个报表需要导出为Excel格式并且包含多个工作表。实际上,这两个查询共享相同的参数,但其他内容都不同。

在Jasper Reports中,如何将报表导出到一个包含多个工作表的Excel文件中(最好来自不同的数据源)?

3个回答

20

感谢这个帖子,它让我更容易创建一个具有多个工作表的Excel导出文件。我发现你可以使用以下方法:

ArrayList<JasperPrint> list = new  ArrayList<JasperPrint>();
list.add(jp1); list.add(jp2);
exporter.setParameter(JRXlsExporterParameter.JASPER_PRINT_LIST, list);

导出器将自动使用每个JasperPrint对象来构建每个工作表;同时,Jasper报告的名称(在jrxml文件中指定)将用作每个工作表的名称。

目前这个解决方案在我的本地项目上运行良好,所以我只是想让你知道。


我之前使用了 JRXlsExporterParameter.SHEET_NAMES 来命名表格,但是在表格标签上的名称顺序错乱了。使用上述代码后,表格名称与正确的表格匹配了。谢谢 +1 - Thomas Kessler
1
请考虑更新您的答案,JRXlsExporter.setParameter已被弃用。 - Petter Friberg

11

多亏了belisarius的链接,我们似乎已经弄清楚了。实现它的基础是像通常一样为每个工作表创建您的JasperPrint对象。所以你需要:

JasperPrint firstWorkSheet = ...;
JasperPrint secondWorkSheet = ...;

JasperPrint对象在此时已经填充了数据源。然后您执行以下操作:

List<JRPrintPage> pages = new ArrayList<JRPrintPage>(secondWorkSheet.getPages());
int i = firstWorkSheet.getPages().size();
for (int count = 0; count < pages.size(); count++) {
    firstWorkSheet.addPage(i, (JRPrintPage) pages.get(count));
    i++;
}
这样做的作用是将 i 设置为当前 firstWorkSheet 中页面的数量(应该是一个)。然后,它遍历 secondWorkSheet 中的页面并将它们添加到 firstWorkSheet 中。
在jasperReport中,确保将其设置为每个工作表jrxml文件打印一页,你就可以进行操作了。如果有任何更改,我会来更新这个,但是这应该有效。
更新:
发现需要使用 net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter 而不是 net.sf.jasperreports.engine.export.JRXlsExporter ,因为在导出到多个工作表时存在问题。
同时, jrxml 文件中的 isIgnorePagination 设置需要为: isIgnorePagination="true" 以便将每个 jrxml 文件导出为单个页面。
然后,您需要将 JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET 参数设置为true,以便将每个页面拆分到单独的工作表中。

3

根据当前版本6.1.1,JRXlsExporter.setParameter已被弃用。它应该被JRXlsExporter.setExporterInput替换。因此,更新后的代码如下:

ArrayList<JasperPrint> sheets = new ArrayList<JasperPrint>();
sheets.add(sheet1); 
sheets.add(sheet2);

exporter.setExporterInput(SimpleExporterInput.getInstance(sheets));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接