好久没更新了,最近在研究java开源报表
JasperReports和 iReport
实际使用效果还不错,美中不足的是没有自带补空行的功能(通过给报表数据增加null值可以实现)和文字旋转(好像不支持带@的旋转字体)
不过应付日常简单报表已经绰绰有余,还是值得记录一下!!!
通过 iReport设计报表请自己学习,比较容易上手,我只贴出调用报表预览打印的相关代码
先上 pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- jasperreports Start -->
<!-- 该包的作用完成ireport中Preview按扭功能。通过该包可以通过java来ireport生成摸班(.jrxml或.jasper)填充数据源并导出pdf,excel,html等格式文件 -->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.10.0</version>
</dependency>
<dependency>
<!-- 生成pdf所依赖的包 -->
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-pdfa</artifactId>
<version>5.4.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<!--将.jrxml编译成.jasper.如果你不使用java编译,而使用ireport工具编译则无须导入该 包 -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.13</version>
</dependency>
<!-- jasperreports End -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<!-- 报表导出Excle所需的包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<span style="color: rgba(0, 0, 255, 1)"><</span><span style="color: rgba(128, 0, 0, 1)">dependency</span><span style="color: rgba(0, 0, 255, 1)">></span>
<span style="color: rgba(0, 0, 255, 1)"><</span><span style="color: rgba(128, 0, 0, 1)">groupId</span><span style="color: rgba(0, 0, 255, 1)">></span>org.springframework.boot<span style="color: rgba(0, 0, 255, 1)"></</span><span style="color: rgba(128, 0, 0, 1)">groupId</span><span style="color: rgba(0, 0, 255, 1)">></span>
<span style="color: rgba(0, 0, 255, 1)"><</span><span style="color: rgba(128, 0, 0, 1)">artifactId</span><span style="color: rgba(0, 0, 255, 1)">></span>spring-boot-starter-test<span style="color: rgba(0, 0, 255, 1)"></</span><span style="color: rgba(128, 0, 0, 1)">artifactId</span><span style="color: rgba(0, 0, 255, 1)">></span>
<span style="color: rgba(0, 0, 255, 1)"><</span><span style="color: rgba(128, 0, 0, 1)">scope</span><span style="color: rgba(0, 0, 255, 1)">></span>test<span style="color: rgba(0, 0, 255, 1)"></</span><span style="color: rgba(128, 0, 0, 1)">scope</span><span style="color: rgba(0, 0, 255, 1)">></span>
<span style="color: rgba(0, 0, 255, 1)"><</span><span style="color: rgba(128, 0, 0, 1)">exclusions</span><span style="color: rgba(0, 0, 255, 1)">></span>
<span style="color: rgba(0, 0, 255, 1)"><</span><span style="color: rgba(128, 0, 0, 1)">exclusion</span><span style="color: rgba(0, 0, 255, 1)">></span>
<span style="color: rgba(0, 0, 255, 1)"><</span><span style="color: rgba(128, 0, 0, 1)">groupId</span><span style="color: rgba(0, 0, 255, 1)">></span>org.junit.vintage<span style="color: rgba(0, 0, 255, 1)"></</span><span style="color: rgba(128, 0, 0, 1)">groupId</span><span style="color: rgba(0, 0, 255, 1)">></span>
<span style="color: rgba(0, 0, 255, 1)"><</span><span style="color: rgba(128, 0, 0, 1)">artifactId</span><span style="color: rgba(0, 0, 255, 1)">></span>junit-vintage-engine<span style="color: rgba(0, 0, 255, 1)"></</span><span style="color: rgba(128, 0, 0, 1)">artifactId</span><span style="color: rgba(0, 0, 255, 1)">></span>
<span style="color: rgba(0, 0, 255, 1)"></</span><span style="color: rgba(128, 0, 0, 1)">exclusion</span><span style="color: rgba(0, 0, 255, 1)">></span>
<span style="color: rgba(0, 0, 255, 1)"></</span><span style="color: rgba(128, 0, 0, 1)">exclusions</span><span style="color: rgba(0, 0, 255, 1)">></span>
<span style="color: rgba(0, 0, 255, 1)"></</span><span style="color: rgba(128, 0, 0, 1)">dependency</span><span style="color: rgba(0, 0, 255, 1)">></span>
<span style="color: rgba(0, 0, 255, 1)"></</span><span style="color: rgba(128, 0, 0, 1)">dependencies</span><span style="color: rgba(0, 0, 255, 1)">></span></pre>
使用jdbc数据源示例
不带参数
1 @RequestMapping("/report2")
2 public void createtopdf(HttpServletRequest request, HttpServletResponse response) throws Exception {
3 Resource resource = new ClassPathResource("templates/report2.jasper");
4 FileInputStream fis = new FileInputStream(resource.getFile());
5 ServletOutputStream os = response.getOutputStream();
6 try {
7 Map parameters = new HashMap<>();
8 Connection conn = getConnection();
9 JasperPrint print = JasperFillManager.fillReport(fis, parameters, conn);
10 JasperExportManager.exportReportToPdfStream(print, os);
11 } catch (JRException e) {
12 e.printStackTrace();
13 } finally {
14 os.flush();
15 }
16 }
17 /**
18 * 返回一个mysql的数据连接对象
19 *
20 * @return
21 * @throws Exception
22 */
23 public Connection getConnection() {
24 String url = "jdbc:mysql://localhost:3306/xxxx?serverTimezone=UTC";
25 try {
26 Class.forName("com.mysql.cj.jdbc.Driver");
27 Connection conn = DriverManager.getConnection(url, "root", "root");
28 return conn;
29 } catch (ClassNotFoundException e) {
30 e.printStackTrace();
31 } catch (SQLException e) {
32 e.printStackTrace();
33 }
34 return null;
35 }
带有参数可以进行数据筛选的
设计报表时设置相应的参数如下
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLzQTM1kDOzQDMy0CMxgTMxMDM1ETNygDMwIDMy0CMwkTNzgTMvwFOwAjMwIzLcBDM5UzM4EzLcd2bsJ2Lc12bj5ycn9Gbi52YuAjMwIzZtl2Lc9CX6MHc0RHaiojIsJye.png)
核心代码如下:
/**
* 可以带有参数筛选的JDBC连接源填充
*
* @param request
* @param response
* @param params
* @throws Exception
*/
@RequestMapping("/params")
public void createpdf33(HttpServletRequest request, HttpServletResponse response, String params) throws Exception {
Resource resource = new ClassPathResource("templates/hasparams.jasper");
FileInputStream fis = new FileInputStream(resource.getFile());
ServletOutputStream os = response.getOutputStream();
try {
Map<String, Object> parameters = new HashMap<>();
parameters.put("id", params);
Connection conn = getConnection();
JasperPrint print = JasperFillManager.fillReport(fis, parameters, conn);
JasperExportManager.exportReportToPdfStream(print, os);
} catch (JRException e) {
e.printStackTrace();
} finally {
os.flush();
}
}
使用javabean作为数据源填充数据调用示例:
/**
* 使用javabean填充数据
*
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/bean2")
public void javabeantest222(HttpServletRequest request, HttpServletResponse response) throws Exception {
Resource resource = new ClassPathResource("templates/bean2.jasper");
FileInputStream fis = new FileInputStream(resource.getFile());
ServletOutputStream os = response.getOutputStream();
try {
Map<String, Object> parameters = new HashMap<>();
List<SysUser> list = getuser();
JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(list);
// Connection conn = getConnection();
JasperPrint print = JasperFillManager.fillReport(fis, parameters, ds);
JasperExportManager.exportReportToPdfStream(print, os);
} catch (JRException e) {
e.printStackTrace();
} finally {
os.flush();
}
}
使用LIst<Map<String,Object>>填充数据调用方式:
/**
* 使用List<Map<String,Object>>集合填充数据
*
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/testmap")
public void testmapcollection(HttpServletRequest request, HttpServletResponse response) throws Exception {
Resource resource = new ClassPathResource("templates/javabean.jasper");
FileInputStream fis = new FileInputStream(resource.getFile());
ServletOutputStream os = response.getOutputStream();
try {
Map<String, Object> parameters = new HashMap<>();
List<Map<String, Object>> list = getMapmodel();
System.out.println(list.toString());
JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(list);
// Connection conn = getConnection();
JasperPrint print = JasperFillManager.fillReport(fis, parameters, ds);
String filename = "javabean";
response.setContentType("application/pdf");
// response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8") + ".pdf");
JasperExportManager.exportReportToPdfStream(print, os);
} catch (JRException e) {
e.printStackTrace();
} finally {
os.flush();
}
}
使用HTML方式预览报表调用代码:
/**
* 预览html格式
*
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/html")
public void testhtml(HttpServletRequest request, HttpServletResponse response) throws Exception {
Resource resource = new ClassPathResource("templates/javabean.jasper");
FileInputStream fis = new FileInputStream(resource.getFile());
ServletOutputStream os = response.getOutputStream();
try {
Map<String, Object> parameters = new HashMap<>();
List<Map<String, Object>> list = getMapmodel();
JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(list);
// Connection conn = getConnection();
JasperPrint print = JasperFillManager.fillReport(fis, parameters, ds);
// JasperExportManager.exportReportToPdfStream(print,os);
JasperExportManager.exportReportToHtmlFile(print, request.getServletContext().getRealPath("/") + "test.html");
response.sendRedirect("test.html");
} catch (JRException e) {
e.printStackTrace();
} finally {
os.flush();
}
}
在服务器端批量转成word代码示例:
/**
* 在服务器端批量导出生成word文件,可以一次性导出多个JasperPrint
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/report.doc")
public void testword(HttpServletRequest request, HttpServletResponse response) throws Exception {
Resource resource = new ClassPathResource("templates/javabean.jasper");
FileInputStream fis = new FileInputStream(resource.getFile());
ServletOutputStream os = response.getOutputStream();
try {
Map<String, Object> parameters = new HashMap<>();
List<Map<String, Object>> list = getMapmodel();
JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(list);
// Connection conn = getConnection();
JasperPrint print = JasperFillManager.fillReport(fis, parameters, ds);
// JasperExportManager.exportReportToPdfStream(print,os);
// JasperExportManager.exportReportToHtmlFile(print, request.getServletContext().getRealPath("/") + "test.html");
// response.sendRedirect("test.html");
JRDocxExporter exporter = new JRDocxExporter();
List<JasperPrint> plist = new ArrayList<>();
plist.add(print);
exporter.setExporterInput(SimpleExporterInput.getInstance(plist));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(new File("D:/javabean.doc")));
exporter.exportReport();
System.out.println(</span>"批量导出word文件成功"<span style="color: rgba(0, 0, 0, 1)">);
} </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (JRException e) {
e.printStackTrace();
} </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)"> {
os.flush();
}
}</span></pre>
直接使用 .jrxml模板先进行代码编译然后调用示例:
/**
* 把jrxml文件编译成 jrasper文件,之后填充数据
* @param request
* @param response
* @throws IOException
* @throws SQLException
*/
@RequestMapping("/compile")
public void Compilejrxml(HttpServletRequest request,HttpServletResponse response)throws IOException,SQLException {
String path = "D:\\Idea Projects\\jasper\\src\\main\\resources\\templates\\report6.jrxml";
File file = new File(path);
String parentPath = file.getParent();
String jrxmlDestSourcePath = parentPath+"/report9.jasper";
try {
JasperCompileManager.compileReportToFile(path,
jrxmlDestSourcePath);
} catch (JRException e) {
e.printStackTrace();
}
File jfile = new File(parentPath+"\\report9.jasper");
FileInputStream fis </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> FileInputStream(jfile);
ServletOutputStream os </span>=<span style="color: rgba(0, 0, 0, 1)"> response.getOutputStream();
</span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> {
Map</span><String, Object> parameters = <span style="color: rgba(0, 0, 255, 1)">new</span> HashMap<><span style="color: rgba(0, 0, 0, 1)">();
List</span><Map<String, Object>> list =<span style="color: rgba(0, 0, 0, 1)"> getMapmodel11();
System.out.println(list.toString());
JRBeanCollectionDataSource ds </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> JRBeanCollectionDataSource(list);
JasperPrint print </span>=<span style="color: rgba(0, 0, 0, 1)"> JasperFillManager.fillReport(fis, parameters, ds);
JasperExportManager.exportReportToPdfStream(print, os);
} </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (JRException e) {
e.printStackTrace();
} </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)"> {
os.flush();
}
}</span></pre>
报表生成pdf并在客户端下载示例:
/**
* 下载报表pdf格式
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/downloadpdf")
public void testmapcollection1234(HttpServletRequest request, HttpServletResponse response) throws Exception {
Resource resource = new ClassPathResource("templates/javabean.jasper");
FileInputStream fis = new FileInputStream(resource.getFile());
ServletOutputStream os = response.getOutputStream();
try {
Map<String, Object> parameters = new HashMap<>();
List<Map<String, Object>> list = getMapmodel();
System.out.println(list.toString());
JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(list);
JasperPrint print = JasperFillManager.fillReport(fis, parameters, ds);
response.setContentType("application/pdf");
response.setCharacterEncoding("UTF-8");
String filename = "javabean";
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8") + ".pdf");
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(print));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(os));
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
exporter.setConfiguration(configuration);
exporter.exportReport();
} catch (JRException e) {
e.printStackTrace();
} finally {
os.flush();
}
}
报表生成Excel并下载至客户端代码:
/**
* 报表下载xls格式
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/downloadxls")
public void testmapcollection12342(HttpServletRequest request, HttpServletResponse response) throws Exception {
Resource resource = new ClassPathResource("templates/javabean.jasper");
FileInputStream fis = new FileInputStream(resource.getFile());
ServletOutputStream os = response.getOutputStream();
try {
Map<String, Object> parameters = new HashMap<>();
List<Map<String, Object>> list = getMapmodel();
System.out.println(list.toString());
JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(list);
JasperPrint print = JasperFillManager.fillReport(fis, parameters, ds);
response.setContentType("application/xls");
response.setCharacterEncoding("UTF-8");
String filename = "javabean";
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8") + ".xls");
JRXlsExporter exporter = new JRXlsExporter();
exporter.setExporterInput(new SimpleExporterInput(print));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(os));
SimpleXlsExporterConfiguration configuration = new SimpleXlsExporterConfiguration();
exporter.setConfiguration(configuration);
exporter.exportReport();
} catch (JRException e) {
e.printStackTrace();
} finally {
os.flush();
}
}
报表生成word格式并下载至客户端代码示例:
/**
* 报表下载word(DOC)格式
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/downloadword")
public void testmapcollection1232342(HttpServletRequest request, HttpServletResponse response) throws Exception {
Resource resource = new ClassPathResource("templates/javabean.jasper");
FileInputStream fis = new FileInputStream(resource.getFile());
ServletOutputStream os = response.getOutputStream();
try {
Map<String, Object> parameters = new HashMap<>();
List<Map<String, Object>> list = getMapmodel();
System.out.println(list.toString());
JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(list);
JasperPrint print = JasperFillManager.fillReport(fis, parameters, ds);
response.setContentType("application/ms-word");
response.setCharacterEncoding("UTF-8");
String filename = "javabean";
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8") + ".doc");
JRDocxExporter exporter = new JRDocxExporter();
exporter.setExporterInput(new SimpleExporterInput(print));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(os));
SimpleDocxExporterConfiguration configuration = new SimpleDocxExporterConfiguration();
exporter.setConfiguration(configuration);
exporter.exportReport();
} </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (JRException e) {
e.printStackTrace();
} </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)"> {
os.flush();
}
}</span></pre>
JasperReports生成的PDF报表会存在中文显示的问题,需要自行设置字体
处理如下
在项目的 resources文件夹下新建文件:
fonts.xml
jasperreports_extension.properties
然后下载ttf的字体文件,放在同级目录下,我下载的时 STSong.ttf 即为宋体
fonts.xml如下
<?xml version="1.0" encoding="UTF-8"?>
<fontFamilies>
<fontFamily name="仿宋">
<normal>STSONG.TTF</normal>
<bold>STSONG.TTF</bold>
<italic>STSONG.TTF</italic>
<boldItalic>STSONG.TTF</boldItalic>
<pdfEncoding>Identity-H</pdfEncoding>
<pdfEmbedded>true</pdfEmbedded>
<exportFonts>
<export key="net.sf.jasperreports.html">'仿宋', Arial, Helvetica, sans-serif</export>
<export key="net.sf.jasperreports.xhtml">'仿宋', Arial, Helvetica, sans-serif</export>
</exportFonts>
</fontFamily>
</fontFamilies>
jasperreports_extension.properties的内容如下
net.sf.jasperreports.extension.registry.factory.simple.font.families=net.sf.jasperreports.engine.fonts.SimpleFontExtensionsRegistryFactory
net.sf.jasperreports.extension.simple.font.families.lobstertwo=fonts.xml
项目的层级如下:
至此,日常简单报表应该已经能彻底满足需求了,代码也比较详细,谢谢大家,有问题可以留言(反正我也不会给你答疑哈哈哈哈)!!!