当前位置:   article > 正文

若依前后端分离框架集成UReport2,保存至数据库并结合业务使用导出

ureport2

一.UReport2概述:

        UReport2是一款基于架构在Spring之上纯Java的高性能报表引擎,通过送代单元格可以实现任意复杂的中国式报表。相比UReport1UReport2重写了全部代码,弥补了UReport1在功能及性能上的各种不足。在UReport2中,提供了全新的基于网页的报表设计器,可以在Chrome、Firefox、Edge等各种主流浏览器运行 (E浏览器除外) 。使用UReport2打开浏览器即可完成各种复杂报表的设计制作。

 文档视频教程地址:

  1. BSDN WIKI: http://wiki.bsdn.org/display/UR/ureport2+Home
  2. w3cschool: https://www.w3cschool.cn/ureport

二.安装配置

1.pom.xml文件中引入ureport2的依赖

  1. <!-- ureport2报表 -->
  2. <dependency>
  3. <groupId>com.bstek.ureport</groupId>
  4. <artifactId>ureport2-console</artifactId>
  5. <version>2.2.9</version>
  6. </dependency>

2.启动类指定xml文件,注册Bean

  1. @ImportResource("classpath:ureport-console-context.xml")
  2. @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
  3. public class RuoYiApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(RuoYiApplication.class, args);
  6. System.out.println("(♥◠‿◠)ノ゙ 若依启动成功 ლ(´ڡ`ლ)゙ \n" +
  7. " .-------. ____ __ \n" +
  8. " | _ _ \\ \\ \\ / / \n" +
  9. " | ( ' ) | \\ _. / ' \n" +
  10. " |(_ o _) / _( )_ .' \n" +
  11. " | (_,_).' __ ___(_ o _)' \n" +
  12. " | |\\ \\ | || |(_,_)' \n" +
  13. " | | \\ `' /| `-' / \n" +
  14. " | | \\ / \\ / \n" +
  15. " ''-' `'-' `-..-' ");
  16. }
  17. @Bean
  18. public ServletRegistrationBean buildUReportServlet(){
  19. return new ServletRegistrationBean(new UReportServlet(),"/ureport/*");
  20. }

3.根据@ImportResource("classpath:ureport-console-context.xml")指定,创建context.xml文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  5. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  6. <import resource="classpath:ureport-console-context.xml" />
  7. <bean id="propertyConfigurer" parent="ureport.props">
  8. <property name="location">
  9. <value>classpath:config.properties</value>
  10. </property>
  11. </bean>
  12. </beans>

若依框架配置层级目录:ruoyi-admin\src\main\resources\context.xml

如果为springboot框架整合,放在resources下即可。

4.根据context.xml指定位置创建ureport配置文件。名为config.properties

  1. ureport.disableHttpSessionReportCache=false
  2. ureport.disableFileProvider=true
  3. ureport.fileStoreDir=/WEB-INF/ureportfiles
  4. ureport.debug=true

5.在ruoyi-framework模块SecurityConfig.java类中加入运行匿名访问,将拦截排除

 此时后端配置完成。启动项目,下图为启动成功。

 访问http://localhost:8080/ureport/designer即可。 

 三.前端配置

1.在ruoyi-ui/vue.config.js添加下列代码

  1. '/ureport': {
  2. target: 'http://localhost:8080',
  3. ws:false,
  4. changeOrigin: true,
  5. pathRewrite: {
  6. '^/ureport': '/ureport'
  7. }
  8. }

 位置如下

2.在views目录下创建ureport/designer,新增index.vue文件。

层级目录:src\views\ureport\designer\index.vue

  1. <template>
  2. <div v-loading="loading" :style="'height:'+ height">
  3. <iframe :src="src" frameborder="no" style="width: 100%;height: 100%" scrolling="auto"/>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. name: "Ureport",
  9. data() {
  10. return {
  11. src: "/ureport/designer",
  12. height: document.documentElement.clientHeight - 94.5 + "px;",
  13. loading: true
  14. };
  15. },
  16. mounted: function() {
  17. setTimeout(() => {
  18. this.loading = false;
  19. }, 230);
  20. const that = this;
  21. window.onresize = function temp() {
  22. that.height = document.documentElement.clientHeight - 94.5 + "px;";
  23. };
  24. }
  25. };
  26. </script>

3.在若依系统新增目录

4.新增菜单

启动项目后可看到

此时可制作报表。 

四.制作报表并保存至数据库

制作报表后,将模板保存至数据库。

首先创建数据库表。

  1. CREATE TABLE `ureport_file_tbl` (
  2. `id_` int(11) NOT NULL AUTO_INCREMENT,
  3. `name_` varchar(100) NOT NULL,
  4. `content_` mediumblob,
  5. `create_time_` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  6. `update_time_` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  7. PRIMARY KEY (`id_`)
  8. ) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4;

重写ureport中crud的接口方法。创建类MySQLProvider。前缀名为指定前缀,在做模板的crud时,调用到ureport底层代码,会根据前缀判断进入的方法。

  1. package com.ruoyi.module.ureport;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.InputStream;
  4. import java.io.UnsupportedEncodingException;
  5. import java.util.ArrayList;
  6. import java.util.Date;
  7. import java.util.List;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Component;
  10. import com.bstek.ureport.provider.report.ReportFile;
  11. import com.bstek.ureport.provider.report.ReportProvider;
  12. import com.ruoyi.module.domain.UreportFileEntity;
  13. import com.ruoyi.module.mapper.UreportFileMapper;
  14. /**
  15. * Mysql 报表存储
  16. * @author hanshiyi
  17. * @version 2023年5月9日
  18. *
  19. */
  20. @Component
  21. // 该注解可以利用其 prefix属性值 + 类的属性名 在yml中配置属性值
  22. // @ConfigurationProperties(prefix = "ureport.mysql.provider")
  23. public class MySQLProvider implements ReportProvider{
  24. private static final String NAME = "mysql-provider";
  25. // 特定前缀,ureport底层会调用 getPrefix 方法来获取报表操作的Provier类
  26. private String prefix = "mysql:";
  27. // 是否禁用
  28. private boolean disabled;
  29. @Autowired
  30. private UreportFileMapper ureportFileMapper;
  31. @Override
  32. public InputStream loadReport(String file)
  33. {
  34. UreportFileEntity ureportFileEntity = ureportFileMapper.queryUreportFileEntityByName(getCorrectName(file));
  35. byte[] content = ureportFileEntity.getContent();
  36. ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
  37. return inputStream;
  38. }
  39. @Override
  40. public void deleteReport(String file)
  41. {
  42. ureportFileMapper.deleteReportFileByName(getCorrectName(file));
  43. }
  44. @Override
  45. public List<ReportFile> getReportFiles()
  46. {
  47. List<UreportFileEntity> list = ureportFileMapper.queryReportFileList();
  48. List<ReportFile> reportList = new ArrayList<>();
  49. for (UreportFileEntity ureportFileEntity : list) {
  50. reportList.add(new ReportFile(ureportFileEntity.getName(), ureportFileEntity.getUpdateTime()));
  51. }
  52. return reportList;
  53. }
  54. @Override
  55. public void saveReport(String file, String content)
  56. {
  57. file = getCorrectName(file);
  58. UreportFileEntity ureportFileEntity = ureportFileMapper.queryUreportFileEntityByName(file);
  59. Date currentDate = new Date();
  60. byte[] cString = null;
  61. try {
  62. cString = content.getBytes("utf-8");
  63. } catch (UnsupportedEncodingException e) {
  64. e.printStackTrace();
  65. }
  66. if(ureportFileEntity == null){
  67. ureportFileEntity = new UreportFileEntity();
  68. ureportFileEntity.setName(file);
  69. ureportFileEntity.setContent(cString);
  70. ureportFileEntity.setCreateTime(currentDate);
  71. ureportFileEntity.setUpdateTime(currentDate);
  72. ureportFileMapper.insertReportFile(ureportFileEntity);
  73. }else{
  74. ureportFileEntity.setContent(cString);
  75. ureportFileEntity.setUpdateTime(currentDate);
  76. ureportFileMapper.updateReportFile(ureportFileEntity);
  77. }
  78. }
  79. @Override
  80. public String getName() {
  81. return NAME;
  82. }
  83. @Override
  84. public boolean disabled() {
  85. return disabled;
  86. }
  87. @Override
  88. public String getPrefix() {
  89. return prefix;
  90. }
  91. /**
  92. * 获取没有前缀的文件名
  93. * @param name
  94. * @return
  95. */
  96. private String getCorrectName(String name)
  97. {
  98. if(name.startsWith(prefix))
  99. {
  100. name = name.substring(prefix.length(), name.length());
  101. }
  102. return name;
  103. }
  104. }

重写方法后,重启项目。保存时会看到

 mysql-provider为数据库保存地址。服务器文件系统为ureport默认保存地址。选择服务器文件系统可保存至系统内,但需要创建保存路径。输入文件名,选择mysql-provider后点击保存,即可保存到数据库中。此处可看到源码UReport2 报表存储与数据源配置_w3cschool

五.与业务结合并导出excel文件(从数据库中获取文件)

保存至数据库后,可以看到保存的文件。

导出excel文件需要创建一个导出excel的工具类。

  1. import com.bstek.ureport.export.ExportConfigureImpl;
  2. import com.bstek.ureport.export.ExportManager;
  3. import java.io.FileOutputStream;
  4. import java.io.OutputStream;
  5. import java.util.Map;
  6. import java.util.Objects;
  7. /**
  8. 导出excel、pdf
  9. */
  10. public class ExportUtils {
  11. public static void exportPdf(ExportManager exportManager, String sourcePath, String targetPath, Map<String, Object> param) throws Exception {
  12. try {
  13. OutputStream fos = new FileOutputStream(targetPath);
  14. try {
  15. ExportConfigureImpl exportConfigure = new ExportConfigureImpl(sourcePath, param, fos);
  16. exportManager.exportPdf(exportConfigure);
  17. } catch (Exception e) {
  18. throw new Exception("exportPdf error", e);
  19. } finally {
  20. if (fos != null) {
  21. try {
  22. fos.close();
  23. }catch(Exception e) {
  24. throw new Exception("exportPdf error", e);
  25. }
  26. }
  27. }
  28. } catch (Exception e) {
  29. throw new Exception("exportPdf error", e);
  30. }
  31. }
  32. public static void exportExcel(ExportManager exportManager, String sourcePath, String targetPath, Map<String, Object> param) throws Exception {
  33. try {
  34. OutputStream fos = new FileOutputStream(targetPath);
  35. try {
  36. String ext = targetPath.substring(targetPath.indexOf(".") + 1);
  37. ExportConfigureImpl exportConfigure = new ExportConfigureImpl(sourcePath, param, fos);
  38. if (Objects.equals(ext, "xls")) {
  39. exportManager.exportExcel97(exportConfigure);
  40. } else {
  41. if (!Objects.equals(ext, "xlsx")) {
  42. throw new Exception("File name is not support!");
  43. }
  44. exportManager.exportExcel(exportConfigure);
  45. }
  46. } catch (Exception e) {
  47. throw new Exception("exportExcel error", e);
  48. } finally {
  49. if (fos != null) {
  50. try {
  51. fos.close();
  52. } catch (Exception e) {
  53. throw new Exception("exportExcel error", e);
  54. }
  55. }
  56. }
  57. } catch (Exception e) {
  58. throw new Exception("exportExcel error", e);
  59. }
  60. }
  61. }

调用工具类方法

ExportUtils.exportExcel(exportManager,sourcePath,filePath,dataMap);

参数可在工具类中看到

第一个参数是调用导出方法的接口,自动注入即可。导出接口源码。

ExportManager接口源码。

  1. import com.bstek.ureport.export.html.HtmlReport;
  2. import java.util.Map;
  3. public interface ExportManager {
  4. String BEAN_ID = "ureport.exportManager";
  5. HtmlReport exportHtml(String var1, String var2, Map<String, Object> var3);
  6. HtmlReport exportHtml(String var1, String var2, Map<String, Object> var3, int var4);
  7. void exportPdf(ExportConfigure var1);
  8. void exportExcel(ExportConfigure var1);
  9. void exportExcel97(ExportConfigure var1);
  10. void exportExcelWithPaging(ExportConfigure var1);
  11. void exportExcel97WithPaging(ExportConfigure var1);
  12. void exportExcelWithPagingSheet(ExportConfigure var1);
  13. void exportExcel97WithPagingSheet(ExportConfigure var1);
  14. void exportWord(ExportConfigure var1);
  15. }

第二个参数sourcePath为String类型,此参数为你想导出模板的名称,对应数据库name的名称。

比如保存到数据库中模板的名称为测试导出模板.ureport.xml。

String sourcePath = "mysql:测试导出模板.ureport.xml";

mysql: 是名称前缀,与重写的MySQLProvider 类中prefix一致。为特定前缀,不写或者写file: 

前者会报错,后者不会进入到重写的MySQLProvider类中的方法,会进入ureport底层默认的查询服务器文件地址。此处重点~

第三个参数filePath为导出文件下载的地址,根据情况写即可。

String filePath = "D:/ureport/xxx.xlsx";

第四个参数dataMap存放写在模板中sql需要的参数。根据业务填写即可。

本文因将模板存储到项目中,部署到服务器后,导出一直报错,找不到模板位置,所以将模板修改至保存到数据库中调用。

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号