一、項目區域的介紹
各塊區域------
Title----報表名,只在第一頁顯示
pageHeader-----放頁碼,時間,創建人,每一頁都會顯示出來
columnHeader-----列名
detail----循環的數據,比如說我們直接從數據庫中得到數據,只用將字段拖到此區域,那麼就會將所有的這個字段的值進行循環了。
-----需要注意的是:table中因爲放了數據,也會將這些數據接着循環。到頭來,本來一個table已經將數據給循環完了,但是又由於detail的循環性質,將整個table又循環了。所以table是不能放在detail中的。這回循環table。
columnFooter-----可以用來統計此列數據。
pageFooter-------每頁底部都會顯示的,如頁碼
lastPageFooter----最後一頁的底部,如日期,簽名.....
Summary--------可能需要對幾頁(你的報表可能有幾個頁組成)的統計值。比如50個銷售記錄共佔用了3頁,那麼放置這些統計記錄的統計值最好的地方就是summary。 Summary只在最後一頁出現。
二、軟件使用
參考:https://jingyan.baidu.com/article/49ad8bce417c405834d8fac9.html
三、非數據源軟件使用(我自己 總結)
3.1動態數據顯示
3.2 table的數據賦值
四,java項目裏寫法
/**
* 打印運輸計劃明細
* @param request
* @return
* @throws ServletException
* @throws IOException
* @throws JRException
*/
@GetMapping("/getPrintTrunkDetail")
public void getPrintTrunkDetail(HttpServletRequest request,HttpServletResponse response) throws JRException, IOException, ServletException {
Map<String,Object> map = getParamMap(request);
Map<String,Object> res = sortingService.getTrunkDetail(map);
List<Map<String,Object>> mlist = new ArrayList<Map<String,Object>>();
Map<String, Object> data = (Map<String, Object>) res.get("topData");
List<Map<String,Object>> tableData = (List<Map<String, Object>>) res.get("bodyData");
System.out.println(tableData.size());
data.put("TABLE_DATA", new JRBeanCollectionDataSource(tableData,false));
data.put("DIST_DEPT_NAME", map.get("DIST_DEPT_NAME"));
mlist.add(data);
File jasperFile = ResourceUtils.getFile("classpath:reportTpl/printtrunk.jrxml");
String jasperPath = jasperFile.getAbsolutePath();
URL url = new URL("file:///"+jasperPath);
InputStream is = url.openStream();
JasperReport jasperReport = JasperCompileManager.compileReport(is);
JasperreportUtils jasperreportUtils = new JasperreportUtils(request, response);
//生成pdf
jasperreportUtils.createExportDocument2(DocType.PDF, map, mlist, "運輸計劃明細",jasperFile);
}
JasperreportUtils:
package com.zywl.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Connection;
import java.text.DecimalFormat;
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 lombok.extern.slf4j.Slf4j;
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.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
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.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRTextExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXmlExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
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;
/**
* @Description jasperreport報表工具類
* @author jiangxy
* @Date 2019-08
*/
@Slf4j
public class JasperreportUtils {
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 parameters
* @param dataSource
* @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) {
log.error("生成html文件錯誤"+ex.getMessage(),ex);
}
return folder + "/" + dpath + "/" + fileName;*/
return null;
}
/**
* 傳入類型,獲取輸出器
*
* @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);
// 一頁一個sheet
configuration.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) {
log.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);
}
/**
* @author yixs
* 生成不同格式報表文檔
* @param docType 文檔類型
* @param jasperPath
*/
@SuppressWarnings("deprecation")
public void createExportDocument2(DocType docType, Map<String, Object> parameters, List<?> list,
String fileName,File jasperFile) throws JRException, IOException, ServletException {
String jasperPath = jasperFile.getAbsolutePath();
URL url = new URL("file:///"+jasperPath);
InputStream is = url.openStream();
JasperReport jasperReport = JasperCompileManager.compileReport(is);
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);
// 一頁一個sheet
configuration.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(jasperReport, 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();
}
}
}
/**
* @author yixs
* 傳入list獲取jasperPrint
* 生成不同格式報表文檔
* @throws JRException
*/
public JasperPrint getJasperPrintWithBeanList( JasperReport jasperReport, 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(jasperReport, parameters, dataSource);
return jasperPrint;
}
}
五、字體的選擇
這時候你會發現中文無法顯示
那你需要軟件導入字體,
同時,java項目依賴導入。
<dependency>
<groupId>com.song</groupId>
<artifactId>myfont</artifactId>
<version>1.0.0</version>
</dependency>
這個是手動打入maven本地
jar包,還有軟件的ttf我會提供