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

打印 上一主题 下一主题

主题 1034|帖子 1034|积分 3102

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
一.UReport2概述:

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


  • BSDN WIKI: http://wiki.bsdn.org/display/UR/ureport2+Home
  • 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.        
  26.         // 特定前缀,ureport底层会调用 getPrefix 方法来获取报表操作的Provier类
  27.         private String prefix = "mysql:";
  28.         // 是否禁用
  29.         private boolean disabled;
  30.         @Autowired
  31.         private UreportFileMapper ureportFileMapper;
  32.         @Override
  33.         public InputStream loadReport(String file)
  34.         {
  35.                 UreportFileEntity ureportFileEntity = ureportFileMapper.queryUreportFileEntityByName(getCorrectName(file));
  36.                 byte[] content = ureportFileEntity.getContent();
  37.                 ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
  38.                 return inputStream;
  39.         }
  40.         @Override
  41.         public void deleteReport(String file)
  42.         {
  43.                 ureportFileMapper.deleteReportFileByName(getCorrectName(file));
  44.         }
  45.         @Override
  46.         public List<ReportFile> getReportFiles()
  47.         {
  48.                 List<UreportFileEntity> list = ureportFileMapper.queryReportFileList();
  49.                 List<ReportFile> reportList = new ArrayList<>();
  50.                 for (UreportFileEntity ureportFileEntity : list) {
  51.                         reportList.add(new ReportFile(ureportFileEntity.getName(), ureportFileEntity.getUpdateTime()));
  52.                 }
  53.                 return reportList;
  54.         }
  55.         @Override
  56.         public void saveReport(String file, String content)
  57.         {
  58.                 file = getCorrectName(file);
  59.                 UreportFileEntity ureportFileEntity = ureportFileMapper.queryUreportFileEntityByName(file);
  60.                 Date currentDate = new Date();
  61.                 byte[] cString = null;
  62.                 try {
  63.                                 cString = content.getBytes("utf-8");
  64.                         } catch (UnsupportedEncodingException e) {
  65.                                 e.printStackTrace();
  66.                         }
  67.                 if(ureportFileEntity == null){
  68.                         ureportFileEntity = new UreportFileEntity();
  69.                         ureportFileEntity.setName(file);
  70.                         ureportFileEntity.setContent(cString);
  71.                         ureportFileEntity.setCreateTime(currentDate);
  72.                         ureportFileEntity.setUpdateTime(currentDate);
  73.                         ureportFileMapper.insertReportFile(ureportFileEntity);
  74.                 }else{
  75.                         ureportFileEntity.setContent(cString);
  76.                            ureportFileEntity.setUpdateTime(currentDate);
  77.                         ureportFileMapper.updateReportFile(ureportFileEntity);
  78.                 }
  79.         }
  80.         @Override
  81.         public String getName() {
  82.                 return NAME;
  83.         }
  84.         @Override
  85.         public boolean disabled() {
  86.                 return disabled;
  87.         }
  88.         @Override
  89.         public String getPrefix() {
  90.                 return prefix;
  91.         }
  92.         /**
  93.          * 获取没有前缀的文件名
  94.          * @param name
  95.          * @return
  96.          */
  97.         private String getCorrectName(String name)
  98.         {
  99.                 if(name.startsWith(prefix))
  100.                 {
  101.                         name = name.substring(prefix.length(), name.length());
  102.                 }
  103.                 return name;
  104.         }
  105. }
复制代码

重写方法后,重启项目。保存时会看到
 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. }
复制代码
调用工具类方法
  1. 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。
  1. String sourcePath = "mysql:测试导出模板.ureport.xml";
复制代码
mysql: 是名称前缀,与重写的MySQLProvider 类中prefix一致。为特定前缀,不写或者写file: 
前者会报错,后者不会进入到重写的MySQLProvider类中的方法,会进入ureport底层默认的查询服务器文件所在。此处重点~
第三个参数filePath为导出文件下载的所在,根据环境写即可。
  1. String filePath = "D:/ureport/xxx.xlsx";
复制代码
第四个参数dataMap存放写在模板中sql需要的参数。根据业务填写即可。

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

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

惊雷无声

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表