Jasperreports+jaspersoft studio学习教程(十一)- JasperReportUtils

本文主要是介绍Jasperreports+jaspersoft studio学习教程(十一)- JasperReportUtils,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

整理了一下用的Utils,更新一下哈!



1、DocType

/*** 定义了报表输出类型,固定了可输出类型* * @author **/
public enum DocType {PDF, HTML, XLS,XLSX, XML, RTF, CSV, TXT, DOC
}


2、DocTypeUtil

/*** 匹配格式* * @author **/
public class DocTypeUtil {/*** 默认类型pdf* @param docType* @return*/public static DocType getEnumDocType(String docType) {DocType type = DocType.PDF;docType = docType.toUpperCase();if (docType.equals("DOC")) {type = DocType.DOC;} else if (docType.equals("XLS")) {type = DocType.XLS;} else if(docType.equals("XLSX")) {type = DocType.XLSX;}else if (docType.equals("XML")) {type = DocType.XML;} else if (docType.equals("RTF")) {type = DocType.RTF;} else if (docType.equals("CSV")) {type = DocType.CSV;} else if (docType.equals("HTML")) {type = DocType.HTML;} else if (docType.equals("TXT")) {type = DocType.TXT;}return type;}
}


3、JasperreportUtils


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Connection;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import cn.cslp.bi.common.ConfigProperties;
import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.HtmlExporter;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRTextExporter;
import net.sf.jasperreports.engine.export.JRTextExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.JRXmlExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.engine.fill.JRFileVirtualizer;
import net.sf.jasperreports.export.ExporterConfiguration;
import net.sf.jasperreports.export.HtmlExporterOutput;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleHtmlExporterOutput;
import net.sf.jasperreports.export.SimpleHtmlReportConfiguration;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimplePdfExporterConfiguration;
import net.sf.jasperreports.export.SimpleTextReportConfiguration;
import net.sf.jasperreports.export.SimpleWriterExporterOutput;
import net.sf.jasperreports.export.SimpleXlsReportConfiguration;
import net.sf.jasperreports.export.SimpleXlsxReportConfiguration;
import net.sf.jasperreports.export.SimpleXmlExporterOutput;
import net.sf.jasperreports.export.XmlExporterOutput;/*** 报表工具类* * @author **/
public class JasperreportUtils {private static final Logger LOGGER = LoggerFactory.getLogger(JasperreportUtils.class);private HttpServletRequest request;private HttpServletResponse response;private HttpSession session;public JasperreportUtils(HttpServletRequest request, HttpServletResponse response) {super();this.request = request;this.response = response;this.session = request.getSession();}/*** datasource与parameters填充报表* * @param jasperPath* @param dataSource* @param parameters* @return* @throws JRException*/public JasperPrint getJasperPrint(String jasperPath, Map<String, Object> parameters, JRDataSource dataSource)throws JRException {JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, parameters, dataSource);return jasperPrint;}/*** connection与parameters填充报表* * @param jasperPath* @param conn* @param parameters* @return* @throws JRException*/public JasperPrint getJasperPrint(String jasperPath, Map<String, Object> parameters, Connection conn)throws JRException {JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, parameters, conn);return jasperPrint;}/*** 传入list获取jasperPrint* * @param jasperPath* @param parameters* @param list* @return* @throws JRException*/public JasperPrint getJasperPrintWithBeanList(String jasperPath, Map<String, Object> parameters, List<?> list)throws JRException {JRDataSource dataSource = null;if(null != list && list.size()> 0) {dataSource = new JRBeanCollectionDataSource(list);}else {dataSource = new JREmptyDataSource();}JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, parameters, dataSource);return jasperPrint;}/*** 获得相应类型的Content type* * @param docType* @return*/public String getContentType(DocType docType) {String contentType = "text/html";switch (docType) {case PDF:contentType = "application/pdf";break;case XLS:contentType = "application/vnd.ms-excel";break;case XLSX:contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";break;case XML:contentType = "text/xml";break;case RTF:contentType = "application/rtf";break;case CSV:contentType = "text/plain";break;case DOC:contentType = "application/msword";break;}return contentType;}/*** jrxml文件 编译为 jasper文件* * @param jrxmlPath* @param jasperPath* @throws JRException*/public void jrxmlToJsper(String jrxmlPath, String jasperPath) throws JRException {JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);}/*** 将pdf输出到浏览器上* * @param jasperPath* @param parameters* @param downloadName* @param dataSource* @throws IOException* @throws JRException*/public void exportPdf(String jasperPath, Map<String, Object> parameters, String downloadName,JRDataSource dataSource) throws IOException, JRException {FileInputStream isRef = new FileInputStream(new File(jasperPath));ServletOutputStream sosRef = response.getOutputStream();;// 放开下载// response.setHeader("Content-Disposition", "attachment;filename=\"" +// downloadName + ".pdf\"");JasperRunManager.runReportToPdfStream(isRef, sosRef, parameters, dataSource);sosRef.flush();sosRef.close();}/*** 生成html文件* @param response* @param list* @param jasperPath* @param fileName* @param parameters* @return*/public String createHtml(HttpServletResponse response, List<?> list, String jasperPath, String fileName,Map<String, Object> parameters, String folder) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");String dpath = sdf.format(new Date());String path = ConfigProperties.getBasicFileDirectory()+"/reportHtml" + folder + "/" + dpath;File file = new File(path);if (!file.exists()) {file.mkdirs();}String htmlFilePath = path + "/" + fileName;try {JRDataSource dataSource = null;if(null != list && list.size()>0) {dataSource = new JRBeanCollectionDataSource(list);}else {dataSource = new JREmptyDataSource();}JasperPrint jasperPrint = this.getJasperPrint(jasperPath, parameters, dataSource);JasperExportManager.exportReportToHtmlFile(jasperPrint, htmlFilePath);} catch (Exception ex) {LOGGER.error("生成html文件错误"+ex.getMessage(),ex);}return folder + "/" + dpath + "/" + fileName;}/*** 传入类型,获取输出器* * @param docType* @return*/@SuppressWarnings("deprecation")public JRAbstractExporter getJRExporter(DocType docType) {JRAbstractExporter exporter = null;switch (docType) {case PDF:exporter = new JRPdfExporter();break;case HTML:exporter = new HtmlExporter();break;case XLS:exporter = new JRXlsExporter();break;case XLSX:exporter = new JRXlsxExporter();break;case XML:exporter = new JRXmlExporter();break;	case RTF:exporter = new JRRtfExporter();break;case CSV:exporter = new JRCsvExporter();break;case DOC:exporter = new JRRtfExporter();break;case TXT:exporter = new JRTextExporter();break;}return exporter;}/*** 生成不同格式报表文档(带缓存)* * @param docType*            文档类型* @param jasperPath*/@SuppressWarnings("deprecation")public void createExportDocument(DocType docType, String jasperPath, Map<String, Object> parameters, List<?> list,String fileName) throws JRException, IOException, ServletException {JRAbstractExporter exporter = getJRExporter(docType);// 获取后缀String ext = docType.toString().toLowerCase();if (!fileName.toLowerCase().endsWith(ext)) {fileName += "." + ext;}// 判断资源类型if (ext.equals("xls")) {SimpleXlsReportConfiguration configuration = new SimpleXlsReportConfiguration();// 删除记录最下面的空行configuration.setRemoveEmptySpaceBetweenRows(Boolean.TRUE);// 一页一个sheetconfiguration.setOnePagePerSheet(Boolean.FALSE);// 显示边框  背景白色configuration.setWhitePageBackground(Boolean.FALSE);exporter.setConfiguration(configuration);}if(ext.equals("xlsx")) {SimpleXlsxReportConfiguration configuration = new SimpleXlsxReportConfiguration();configuration.setRemoveEmptySpaceBetweenRows(Boolean.TRUE);configuration.setRemoveEmptySpaceBetweenColumns(Boolean.TRUE);configuration.setWhitePageBackground(Boolean.FALSE);//自动选择格式configuration.setDetectCellType(Boolean.TRUE);exporter.setConfiguration(configuration);}if (ext.equals("txt")) {SimpleTextReportConfiguration configuration = new SimpleTextReportConfiguration();configuration.setCharWidth((float)10);configuration.setCharHeight((float)15);exporter.setConfiguration(configuration);}response.setContentType(getContentType(docType));response.setHeader("Content-Disposition","attachment; filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));//加缓存JRFileVirtualizer virtualizer = new JRFileVirtualizer(2, ConfigProperties.getBasicFileDirectory() + "/temp");parameters.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);virtualizer.setReadOnly(true);exporter.setExporterInput(new SimpleExporterInput(getJasperPrintWithBeanList(jasperPath, parameters, list)));/*exporter.setParameter(JRExporterParameter.JASPER_PRINT,getJasperPrintWithBeanList(jasperPath, parameters, list));*/OutputStream outStream = null;PrintWriter outWriter = null;// 解决中文乱码问题response.setCharacterEncoding("UTF-8");if (ext.equals("csv") || ext.equals("doc") || ext.equals("rtf") || ext.equals("txt")) {outWriter = response.getWriter();SimpleWriterExporterOutput outPut = new SimpleWriterExporterOutput(outWriter);exporter.setExporterOutput(outPut);//exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, outWriter);} else {if(ext.equals("xml")) {outWriter = response.getWriter();XmlExporterOutput outPut  = new SimpleXmlExporterOutput(outWriter);exporter.setExporterOutput(outPut);}else if(ext.equals("html")){outWriter = response.getWriter();HtmlExporterOutput outPut = new SimpleHtmlExporterOutput(outWriter);exporter.setExporterOutput(outPut);}else {outStream = response.getOutputStream();exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outStream));}}try {exporter.exportReport();virtualizer.cleanup();} catch (JRException e) {throw new ServletException(e);} finally {if (outStream != null) {try {outStream.close();} catch (IOException ex) {}}if(outWriter != null) {outWriter.close();}}}/*** 输出以分页的形式输出html* @param jasperPath* @param parameters* @param list* @throws JRException* @throws IOException*/public void createHtmlByPage(JasperPrint jasperPrint,String pageStr) throws JRException, IOException {int pageIndex = 0;int lastPageIndex = 0;HtmlExporter exporter = new HtmlExporter();if(null != jasperPrint.getPages()) {lastPageIndex = jasperPrint.getPages().size() - 1;}if(null == pageStr) {pageStr = "0";}try {pageIndex = Integer.valueOf(pageStr);if(pageIndex > 0) {pageIndex = pageIndex -1 ;}} catch (Exception e) {// 如果得到的非数字字符串if("lastPage".equals(pageStr)) {pageIndex = lastPageIndex;}}if (pageIndex < 0) {pageIndex = 0;}if (pageIndex > lastPageIndex) {pageIndex = lastPageIndex;}response.setCharacterEncoding("UTF-8");try {PrintWriter out = response.getWriter();exporter.setExporterInput(new SimpleExporterInput(jasperPrint));SimpleHtmlReportConfiguration configuration =  new SimpleHtmlReportConfiguration();configuration.setPageIndex(pageIndex);exporter.setConfiguration(configuration);//exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);HtmlExporterOutput outPut = new SimpleHtmlExporterOutput(out);exporter.setExporterOutput(outPut);exporter.exportReport();} catch (Exception e) {e.printStackTrace();}}/*** 批量打印pdf文件*/public void exportBatchPdf(List<JasperPrint> jasperPrintList,String fileName) {JRPdfExporter exporter =  new JRPdfExporter();try {/*** 注入打印模板*/exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));OutputStream outStream = null;response.setContentType(getContentType(DocType.PDF));response.setHeader("Content-Disposition","attachment; filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));outStream = response.getOutputStream();exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outStream));//配置项SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();// 是否批量打印configuration.setCreatingBatchModeBookmarks(true);// 是否加密configuration.setEncrypted(false);exporter.setConfiguration(configuration);exporter.exportReport();} catch (Exception e) {e.printStackTrace();}}/*** 千分位格式化数据 保留两位小数,且 ‘0 ’ 转为 ‘--’* * @param obj* @param fieldNames*            需转化的属性* @return*/public Object toFormatNumber(Object obj, String[] fieldNames) {Class clazz = (Class) obj.getClass();Field[] fs = clazz.getDeclaredFields();for (int i = 0; i < fs.length; i++) {Field f = fs[i];// 设置些属性是可以访问的f.setAccessible(true);String type = f.getType().toString();Object val = null;try {for (String str : fieldNames) {if (f.getName() == str) {val = f.get(obj);}}if (null != val) {if (type.endsWith("String")) {if (val.equals("0")) {f.set(obj, "--");} else {/** ; BigDecimal str=new BigDecimal((String) val); DecimalFormat df=new* DecimalFormat(",###,##0.00");*/ // 保留两位小数f.set(obj, this.toNumeber((String) val));}} else if (type.endsWith("int") || type.endsWith("Integer")) {// System.out.println(f.getType()+"\t");} else {// System.out.println(f.getType()+"\t");}}} catch (Exception ex) {LOGGER.error("千分位格式化数据错误"+ex.getMessage(), ex);}}return obj;}/*** 转为万元保留小数点后两位* * @param value* @return*/private String toNumeber(String value) {Double number = Double.valueOf(value) / 10000.00;BigDecimal str = new BigDecimal(number);DecimalFormat df = new DecimalFormat(",###,##0.00");return df.format(str);}}

这篇关于Jasperreports+jaspersoft studio学习教程(十一)- JasperReportUtils的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/465028

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

【学习笔记】 陈强-机器学习-Python-Ch15 人工神经网络(1)sklearn

系列文章目录 监督学习:参数方法 【学习笔记】 陈强-机器学习-Python-Ch4 线性回归 【学习笔记】 陈强-机器学习-Python-Ch5 逻辑回归 【课后题练习】 陈强-机器学习-Python-Ch5 逻辑回归(SAheart.csv) 【学习笔记】 陈强-机器学习-Python-Ch6 多项逻辑回归 【学习笔记 及 课后题练习】 陈强-机器学习-Python-Ch7 判别分析 【学

系统架构师考试学习笔记第三篇——架构设计高级知识(20)通信系统架构设计理论与实践

本章知识考点:         第20课时主要学习通信系统架构设计的理论和工作中的实践。根据新版考试大纲,本课时知识点会涉及案例分析题(25分),而在历年考试中,案例题对该部分内容的考查并不多,虽在综合知识选择题目中经常考查,但分值也不高。本课时内容侧重于对知识点的记忆和理解,按照以往的出题规律,通信系统架构设计基础知识点多来源于教材内的基础网络设备、网络架构和教材外最新时事热点技术。本课时知识