jasper生成动态报表
业务:客户点击链接(get请求),在页面显示报表。根据请求信息动态获取报表。
环境/工具:springboot ,IDEA编译器, TIBCO JasperSoftTIBCO JasperSoft 下载地址(百度云)
链接:https://pan.baidu.com/s/12AE1be2NW_2zpGFtoN52_A
提取码:yin8
配置依赖
添加工具类
创建测试类
测试
下载Jaspersoft
绘制报表
生成jasper文件
修改jrxml
Step1 Maven依赖
<!-- <dependencies>下-->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.0.3</version>
</dependency>
<!--报表相关-->
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.7</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-fonts</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-pdfa</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.9</version>
</dependency>
<!-- //如果直接使用文中附出的工具类,该依赖虽然不会被调用,但是不加上会报错-->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.2.2</version>
</dependency>
<!-- <build><plugins>下-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<configuration>
<!--<encoding>UTF-8</encoding>-->
<nonFilteredFileExtensions>
<nonFilteredFileExtension>p12</nonFilteredFileExtension>
<nonFilteredFileExtension>xls</nonFilteredFileExtension>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
<nonFilteredFileExtension>jrxml</nonFilteredFileExtension>
<nonFilteredFileExtension>jasper</nonFilteredFileExtension>
<nonFilteredFileExtension>ttf</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
Step 2 工具类
1.JasperHelper.java
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.base.JRBaseReport;
import net.sf.jasperreports.engine.export.*;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.sql.Connection;
import java.util.Base64;
import java.util.Map;
@SuppressWarnings("deprecation")
public class JasperHelper {
public static final String PRINT_TYPE = "print";
public static final String PDF_TYPE = "pdf";
public static final String EXCEL_TYPE = "excel";
public static final String HTML_TYPE = "html";
public static final String WORD_TYPE = "word";
public static enum DocType {
PDF, HTML, XLS, XML, RTF
}
@SuppressWarnings("rawtypes")
public static JRAbstractExporter getJRExporter(DocType docType) {
JRAbstractExporter exporter = null;
switch (docType) {
case PDF:
exporter = new JRPdfExporter();
break;
case HTML:
exporter = new JRHtmlExporter();
break;
case XLS:
exporter = new JExcelApiExporter();
break;
case XML:
exporter = new JRXmlExporter();
break;
case RTF:
exporter = new JRRtfExporter();
break;
}
return exporter;
}
public static String showPdf(String type1, String reportfile, Map parameters, JRDataSource conn, String type) throws Exception {
// request.setCharacterEncoding("utf-8");
// response.setCharacterEncoding("utf-8");
// response.setContentType("text/html");
// response.setContentType("application/pdf");
JRAbstractExporter exporter = getJRExporter(JasperHelper.DocType.PDF);
JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile, parameters, conn);
// request.getSession().setAttribute("net.sf.jasperreports.j2ee.jasper_print", jasperPrint);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
exporter.exportReport();
byte[] bytes = baos.toByteArray();
File file = new File("/usr/local/src/huier-product/print/1.pdf");
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes);
fos.close();
//pdf转图片
if(type1.equals("barcode")){
PdfUtil.pdf2pngBarcode("/usr/local/src/huier-product/print","1");
}else {
PdfUtil.pdf2pngShunFeng("/usr/local/src/huier-product/print","1");
}
// PdfUtil.pdf2png("/usr/local/src/huier-product/print","1");
// File image = new File("D:\\apache-tomcat-6.0.29\\imag\\1.png");
String base = fileToBase64("/usr/local/src/huier-product/print/1.png");
return base;
// printUtil.drawImage("D:\\apache-tomcat-6.0.29\\imag\\1.jpg", type1);
}
public static String showPdf(JasperPrint jasperPrint) throws Exception {
JRAbstractExporter exporter = getJRExporter(JasperHelper.DocType.PDF);
JasperPrint jasperPrint1=jasperPrint;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint1);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
exporter.exportReport();
byte[] bytes = baos.toByteArray();
File file = new File("/usr/local/src/huier-product/print/1.pdf");
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes);
fos.close();
String base = fileToBase64("/usr/local/src/huier-product/print/1.png");
return base;
}
public static String fileToBase64(String path) {
String base64 = null;
InputStream in = null;
try {
File file = new File(path);
in = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
in.read(bytes);
base64 = Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return base64;
}
public static void showPdf(String defaultFilename, String reportfile, HttpServletRequest request, HttpServletResponse response, Map parameters, Connection conn) throws JRException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
response.setContentType("application/pdf");
JRAbstractExporter exporter = getJRExporter(JasperHelper.DocType.PDF);
JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile, parameters, conn);
request.getSession().setAttribute("net.sf.jasperreports.j2ee.jasper_print", jasperPrint);
OutputStream out = response.getOutputStream();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
exporter.exportReport();
out.flush();
}
public static void prepareReport(JasperReport jasperReport, String type) {
/*
* 如果导出的是excel,则需要去掉周围的margin
*/
if ("excel".equals(type))
try {
Field margin = JRBaseReport.class
.getDeclaredField("leftMargin");
margin.setAccessible(true);
margin.setInt(jasperReport, 0);
margin = JRBaseReport.class.getDeclaredField("topMargin");
margin.setAccessible(true);
margin.setInt(jasperReport, 0);
margin = JRBaseReport.class.getDeclaredField("bottomMargin");
margin.setAccessible(true);
margin.setInt(jasperReport, 0);
Field pageHeight = JRBaseReport.class
.getDeclaredField("pageHeight");
pageHeight.setAccessible(true);
pageHeight.setInt(jasperReport, 2147483647);
} catch (Exception exception) {
}
}
/**
* 导出excel
*/
public static void exportExcel(JasperPrint jasperPrint,
String defaultFilename, HttpServletRequest request,
HttpServletResponse response) throws IOException, JRException {
/*
* 设置头信息
*/
response.setContentType("application/vnd.ms-excel");
String defaultname = null;
if (defaultFilename.trim() != null && defaultFilename != null) {
defaultname = defaultFilename + ".xls";
} else {
defaultname = "export.xls";
}
response.setHeader("Content-Disposition", "attachment; filename=\""
+ URLEncoder.encode(defaultname, "UTF-8") + "\"");
ServletOutputStream ouputStream = response.getOutputStream();
JRXlsExporter exporter = new JRXlsExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
exporter.setParameter(
JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
Boolean.TRUE); // 删除记录最下面的空行
exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
Boolean.FALSE);// 删除多余的ColumnHeader
//
exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,
Boolean.FALSE);// 显示边框
exporter.exportReport();
ouputStream.flush();
ouputStream.close();
}
/**
* 导出pdf,注意此处中文问题,
*
* 这里应该详细说:主要在ireport里变下就行了。看图
*
* 1)在ireport的classpath中加入iTextAsian.jar 2)在ireport画jrxml时,看ireport最左边有个属性栏。
*
* 下边的设置就在点字段的属性后出现。 pdf font name :STSong-Light ,pdf encoding :UniGB-UCS2-H
*/
private static void exportPdf(JasperPrint jasperPrint,
String defaultFilename, HttpServletRequest request,
HttpServletResponse response) throws IOException, JRException {
response.setContentType("application/pdf");
String defaultname = null;
if (defaultFilename.trim() != null && defaultFilename != null) {
defaultname = defaultFilename + ".pdf";
} else {
defaultname = "export.pdf";
}
String fileName = new String(defaultname.getBytes("GBK"), "ISO8859_1");
response.setHeader("Content-disposition", "attachment; filename="
+ fileName);
ServletOutputStream ouputStream = response.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream);
ouputStream.flush();
ouputStream.close();
}
/**
* 导出html
*/
private static void exportHtml(JasperPrint jasperPrint,
String defaultFilename, HttpServletRequest request,
HttpServletResponse response) throws IOException, JRException {
response.setContentType("text/html");
ServletOutputStream ouputStream = response.getOutputStream();
JRHtmlExporter exporter = new JRHtmlExporter();
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
Boolean.FALSE);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
//设置图片文件存放路径,此路径为服务器上的绝对路径
String imageDIR =request.getSession().getServletContext().getRealPath("/");
exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR_NAME, imageDIR);
//设置图片请求URI
String imageURI = request.getContextPath() + "/";
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageURI);
//设置导出图片到图片存放路径
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.TRUE);
exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
exporter.exportReport();
ouputStream.flush();
ouputStream.close();
}
/**
* 导出word
*/
@SuppressWarnings("rawtypes")
private static void exportWord(JasperPrint jasperPrint,
String defaultFilename, HttpServletRequest request,
HttpServletResponse response) throws JRException, IOException {
response.setContentType("application/msword;charset=utf-8");
String defaultname = null;
if (defaultFilename.trim() != null && defaultFilename != null) {
defaultname = defaultFilename + ".doc";
} else {
defaultname = "export.doc";
}
String fileName = new String(defaultname.getBytes("GBK"), "utf-8");
response.setHeader("Content-disposition", "attachment; filename="
+ fileName);
JRExporter exporter = new JRRtfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
response.getOutputStream());
exporter.exportReport();
}
/**
* 按照类型导出不同格式文件
*
* 数据
* @param type
* 文件类型
* @param is
* jasper文件的来源
* @param request
* @param response
*/
public static void export(String type, String defaultFilename, File is,
HttpServletRequest request, HttpServletResponse response,
Map parameters, Connection conn) {
try {
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
prepareReport(jasperReport, type);
JasperPrint jasperPrint = JasperFillManager.fillReport(
jasperReport, parameters, conn);
if (EXCEL_TYPE.equals(type)) {
exportExcel(jasperPrint, defaultFilename, request, response);
} else if (PDF_TYPE.equals(type)) {
exportPdf(jasperPrint, defaultFilename, request, response);
} else if (HTML_TYPE.equals(type)) {
exportHtml(jasperPrint, defaultFilename, request, response);
} else if (WORD_TYPE.equals(type)) {
exportWord(jasperPrint, defaultFilename, request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void export(String type, String defaultFilename, File is,
HttpServletRequest request, HttpServletResponse response,
Map parameters, JRDataSource conn) {
try {
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
prepareReport(jasperReport, type);
JasperPrint jasperPrint = JasperFillManager.fillReport(
jasperReport, parameters, conn);
if (EXCEL_TYPE.equals(type)) {
exportExcel(jasperPrint, defaultFilename, request, response);
} else if (PDF_TYPE.equals(type)) {
exportPdf(jasperPrint, defaultFilename, request, response);
} else if (HTML_TYPE.equals(type)) {
exportHtml(jasperPrint, defaultFilename, request, response);
} else if (WORD_TYPE.equals(type)) {
exportWord(jasperPrint, defaultFilename, request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 输出html静态页面,必须注入request和response
*
* 报表文件使用的图片路径,比如 ../servlets/image?image=
* @throws JRException
* @throws IOException
*/
public static void showHtml(String defaultFilename, String reportfile,
HttpServletRequest request, HttpServletResponse response, Map parameters,
JRDataSource conn) throws JRException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
JRAbstractExporter exporter = getJRExporter(DocType.HTML);
JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile,
parameters, conn);
request.getSession().setAttribute(
ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
jasperPrint);
PrintWriter out = response.getWriter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
exporter.setParameter(
JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
Boolean.FALSE);
//设置图片文件存放路径,此路径为服务器上的绝对路径
String imageDIR =request.getSession().getServletContext().getRealPath("/");
exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR_NAME, imageDIR);
//设置图片请求URI
String imageURI = request.getContextPath() + "/";
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageURI);
//设置导出图片到图片存放路径
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.TRUE);
exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
exporter.exportReport();
out.flush();
}
public static void showHtml(String defaultFilename, String reportfile,
HttpServletRequest request, HttpServletResponse response, Map parameters,
Connection conn) throws JRException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
JRAbstractExporter exporter = getJRExporter(DocType.HTML);
JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile,
parameters, conn);
request.getSession().setAttribute(
ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
jasperPrint);
PrintWriter out = response.getWriter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);
exporter.setParameter(
JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
Boolean.FALSE);
//设置图片文件存放路径,此路径为服务器上的绝对路径
String imageDIR =request.getSession().getServletContext().getRealPath("/");
exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR_NAME, imageDIR);
//设置图片请求URI
String imageURI = request.getContextPath() + "/";
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageURI);
//设置导出图片到图片存放路径
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.TRUE);
exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
exporter.exportReport();
out.flush();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void showPdf(String defaultFilename, String reportfile,
HttpServletRequest request, HttpServletResponse response, Map parameters,
JRDataSource conn) throws JRException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
response.setContentType("application/pdf");
JRAbstractExporter exporter = getJRExporter(DocType.PDF);
JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile,
parameters, conn);
request.getSession().setAttribute(
ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
jasperPrint);
OutputStream out = response.getOutputStream();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
exporter.exportReport();
out.flush();
}
public static void showPdf(String defaultFilename, HttpServletRequest request, HttpServletResponse response, JasperPrint jasperPrint) throws JRException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
response.setContentType("application/pdf");
JRAbstractExporter exporter = getJRExporter(JasperHelper.DocType.PDF);
JasperPrint jasperPrint1 = jasperPrint;
request.getSession().setAttribute("net.sf.jasperreports.j2ee.jasper_print", jasperPrint1);
OutputStream out = response.getOutputStream();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint1);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
exporter.exportReport();
out.flush();
}
}
2.PdfUtil
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
public class PdfUtil {
/**
* 转换全部的pdf
* @param fileAddress 文件地址
* @param filename PDF文件名
*/
public static void pdf2pngBarcode(String fileAddress, String filename) {
// 将pdf装图片 并且自定义图片得格式大小
File file = new File(fileAddress+"/"+filename+".pdf");
try {
PDDocument doc = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(doc);
int pageCount = doc.getNumberOfPages();
for (int i = 0; i < pageCount; i++) {
BufferedImage image = renderer.renderImageWithDPI(i, 200); // Windows native DPI
// BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
ImageIO.write(image, "PNG", new File(fileAddress+"/"+filename+".png"));
// changeSize(150, 100, fileAddress + "/" + filename + ".png");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void pdf2pngShunFeng(String fileAddress, String filename) {
// 将pdf装图片 并且自定义图片得格式大小
File file = new File(fileAddress + "/" + filename + ".pdf");
try {
PDDocument doc = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(doc);
int pageCount = doc.getNumberOfPages();
for (int i = 0; i < pageCount; i++) {
BufferedImage image = renderer.renderImageWithDPI(i, 200); // Windows native DPI
// BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
ImageIO.write(image, "PNG", new File(fileAddress + "/" + filename + ".png"));
// changeSize(400, 600, fileAddress + "/" + filename + ".png");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean changeSize(int newWidth, int newHeight, String path) {
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(path));
//字节流转图片对象
Image bi = ImageIO.read(in);
//构建图片流
BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
//绘制改变尺寸后的图
tag.getGraphics().drawImage(bi, 0, 0, newWidth, newHeight, null);
//输出流
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path));
//JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//encoder.encode(tag);
ImageIO.write(tag, "PNG", out);
in.close();
out.close();
return true;
} catch (IOException e) {
return false;
}
}
}
Step3 测试类(利用SpringMVC直接配置)
package hdu.huier.huierbusiness.controller;
import hdu.huier.huierbusiness.utils.JasperHelper;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* @Author: Yin
* @Date: 2020/7/4 15:21
*/
@CrossOrigin
@RestController
@EnableTransactionManagement
@RequestMapping("/report")
public class ReportController {
@Value("${FilePath}")
String FilePath;
@Value("${spring.datasource.druid.datasource1.url}")
String url;
@Value("${spring.datasource.druid.datasource1.username}")
String username;
@Value("${spring.datasource.druid.datasource1.password}")
String password;
@GetMapping({"/huierReport"})
@ResponseBody
public void huierPrint(HttpServletRequest request, HttpServletResponse response, String s) throws Exception, IOException, JRException {
//此处使用的pojo类必须和模板文件中的类一致,否则无法正确生成.
HashMap<String,Object> hashMap = new HashMap<>(2);
//这里的参数名与参数类型都要与jasper报表中的一致
hashMap.put("stoid",1L);
hashMap.put("stogctid","1212");
List<HashMap> userList = Arrays.asList(hashMap,hashMap);
//模拟数据源
JRDataSource jrDataSource = new JRBeanCollectionDataSource(userList);
File reporeFile = new File(this.FilePath + "/pp.jasper");
// 参数说明: 文件名 jasper文件路径 请求 回复 请求参数(Map) 数据库连接
JasperHelper.showPdf("test1", reporeFile.getPath(), request, response, new HashMap(), jrDataSource);
}
@GetMapping({"/huierReport2"})
@ResponseBody
public void huierPrint2(HttpServletRequest request, HttpServletResponse response, String s) throws Exception, IOException, JRException {
HashMap<String,Object> t = new HashMap<>();
t.put("ceshi","1");
String dburl = this.url;
String dbuser = this.username;
String dbpassword = this.password;
Connection conn = DriverManager.getConnection(dburl, dbuser, dbpassword);
File reporeFile = new File(this.FilePath + "/p3.jasper");
JasperHelper.showPdf("test2", reporeFile.getPath(), request, response, t, conn);
}
}
到这里我们就把环境配好了,现在我们需要进行报表的编辑,也就是生成jrxml,jasper文件。
Step4 绘制报表
打开TIBCO Jaspersoft
看到页面如下:【这里报表的绘制不多做介绍,看参看其他博主教程,这里附上一个链接:】
现在假如绘制了这样一张报表:
然后点击preview,会显示这样的数据:
然后点击build 获取jasper文件
这样,一张静态报表就完成了,放到合适的路径,就可以回到step3进行测试了。
Step5 实现动态sql
刚才已经实现了报表的生成,但还是达不到我们的需求,我们要将刚才的静态sql改成动态sql。我们去修改jrxml部分代码实现动态sql。
点击Source,进行xml查看
改成下面的样子
然后进行build,形成新的jasper。回到step3
@GetMapping({"/huierReport2"})
@ResponseBody
public void huierPrint2(HttpServletRequest request, HttpServletResponse response,@RequestParam String nioid) throws Exception, IOException, JRException {
HashMap<String,Object> t = new HashMap<>();
t.put("nioid",nioid);
String dburl = this.url;
String dbuser = this.username;
String dbpassword = this.password;
Connection conn = DriverManager.getConnection(dburl, dbuser, dbpassword);
File reporeFile = new File(this.FilePath + "/2p.jasper");
JasperHelper.showPdf("test2", reporeFile.getPath(), request, response, t, conn);
}
最后,访问路径,即可动态获取报表
成功 撒花