配置文件baobiao.properties:
#export file path
basePath=D:\\zip\\
#single report file name
reportName1=\u5168\u6C11\u4ED8\u5BA2\u6237\u7AEF\u7EDF\u8BA1\u8868.html
reportName2=\u5168\u6C11\u4ED8\u5F53\u65E5\u4EA4\u6613\u6D41\u6C34.html
#report file path
reportFilePath1=reports\\baobiaozsorder.jasper
reportFilePath2=reports\\qmfDayTransaction.jasper
读取配置文件类PropertiesReader:
public static Properties getPropertyFileContent(){
Properties props = new Properties();
try {
prop.load(PropertiesReader.class.getClassLoader().getResourceAsStream("baobiao.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
controller方法:
@RequestMapping(value = "/download.do", method = RequestMethod.POST)
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
Properties props = PropertiesReader.getPropertyFileContent();
Set<Entry<Object, Object>> set = props.entrySet();
//计数,生成报表数量
int count = 0;
//单个报表名称
//String reportName1 = "全民付客户端统计表.html", reportName2 = "全民付当日交易流水.html";
List<String> reportNames = new ArrayList<String>();
//报表模板文件存放目录
//String reportFilePath1 = "reports\\baobiaozsorder.jasper", reportFilePath2 = "reports\\qmfDayTransaction.jasper";
List<String> reportFilePaths = new ArrayList<String>();
for (Entry<Object, Object> entry : set) {
String key = entry.getKey().toString();
String value = entry.getValue().toString();
if(key.contains("reportName")){
reportNames.add(value);
count++;
}
if(key.contains("reportFilePath")){
reportFilePaths.add(value);
}
}
// 设置压缩包名称
String fileName = "报表-" + CommonUtil.getTodayStr() + ".zip";
//检查是否已下载
//报表压缩文件存放目录
String basePath = props.getProperty("basePath");
//"D:\\zip\\";
String filePath = basePath + fileName;
File file = new File(filePath);
if(!file.exists()){
List<OutputStream> oss = new ArrayList<OutputStream>();
Connection con = null;
try {
con = dataSource.getConnection();
for (int i = 0; i < count; i++) {
OutputStream os = GenerateReport.baobiao(reportFilePaths.get(i), con);
oss.add(os);
}
} catch (Exception e1) {
logger.error("报表生成出现错误", e1);
} finally{
try {
for (int i = 0; i < oss.size(); i++) oss.get(i).flush();
con.close();
} catch (Exception e) {}
}
OutputStream os = null;
CheckedOutputStream cos = null;
ZipOutputStream zipOut = null;
try {
os = response.getOutputStream();
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(fileName.getBytes("gb2312"), "iso8859-1"));
// 对输出文件做CRC32校验
cos = new CheckedOutputStream(os, new CRC32());
zipOut = new ZipOutputStream(cos);
// 设置编码
zipOut.setEncoding("UTF-8");
// 将单个文件的流添加到压缩文件中
for (int i = 0; i < count; i++) {
GenerateReport.compressFile(oss.get(i), zipOut, reportNames.get(i));
}
/**
* zip写入磁盘
*/
zipOut.flush();zipOut.close();
os.flush();
os = new FileOutputStream(new File(filePath));
zipOut = new ZipOutputStream(os);
// 设置编码
zipOut.setEncoding("UTF-8");
// 将单个文件的流添加到压缩文件中
for (int i = 0; i < count; i++) GenerateReport.compressFile(oss.get(i), zipOut, reportNames.get(i));
} catch (Exception e) {
logger.error("报表打包出现错误", e);
} finally {
try {
zipOut.flush();zipOut.close();
cos.close();
os.close();
for (int i = 0; i < oss.size(); i++) oss.get(i).close();
} catch (IOException e) {}
}
}else{
FileInputStream is = null;
OutputStream os = null;
int buffer = 1024 * 2;
try {
os = response.getOutputStream();
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(fileName.getBytes("gb2312"), "iso8859-1"));
is = new FileInputStream(file);
byte[] data = new byte[buffer];
int len = -1;
while ((len = is.read(data, 0, buffer)) != -1) {
os.write(data, 0, len);
}
}catch (Exception e) {
logger.error("报表打包出现错误", e);
} finally {
try {
os.close();
is.close();
} catch (IOException e) {}
}
}
}
辅助工具类GenerateReport:
package com.buybal.ums.mgr.util;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
public class GenerateReport {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
private static Log log = LogFactory.getLog(GenerateReport.class);
/**
* 使用jspaer文件创建报表
* @param reportFilePath 模板位置
* @param con 数据源连接
* @return 返回流
* @throws JRException
* @throws ClassNotFoundException
* @throws SQLException
* @throws IOException
*/
public static OutputStream baobiao(String reportFilePath, Connection con) throws JRException,
ClassNotFoundException, SQLException, IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(os);
JRHtmlExporter exporter = new JRHtmlExporter();
JasperPrint jasperPrint = null;
InputStream inputStream = GenerateReport.class.getClassLoader()
.getResourceAsStream(reportFilePath);
Map<String, Object> parameters = new HashMap<String, Object>();// 传入参数
parameters.put("reportTitle", "我的第一个程序");
jasperPrint = JasperFillManager
.fillReport(inputStream, parameters, con);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, writer);
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,Boolean.FALSE);
exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "GBK");
exporter.exportReport();
/*
* JasperExportManager.exportReportToHtmlFile( jasperPrint,
* "D:\\baobiaozsorderJasperReport" + simpleDateFormat.format(new
* Date()) + ".html");
*/
return os;
}
/**
* 打包zip
* @param os 单个文件输出流,只能是ByteArrayOutputStream类型,便于转输入流
* @param out zip输出流
* @param fileName zip文件名
* @throws IOException
*/
public static void compressFile(OutputStream os, ZipOutputStream out, String fileName) throws IOException {
int buffer = 1024 * 2;
// 输出流转换为输入流
ByteArrayOutputStream bos = (ByteArrayOutputStream) os;
InputStream is = new ByteArrayInputStream(bos.toByteArray());
BufferedInputStream bis = new BufferedInputStream(is);
ZipEntry entry = new ZipEntry(fileName);
out.putNextEntry(entry);
int count;
byte data[] = new byte[buffer];
while ((count = bis.read(data, 0, buffer)) != -1) {
out.write(data, 0, count);
}
bis.close();
}
}
注:打包zip需要ant.jar
本文介绍了一种报表生成和压缩的方法,通过Java实现从数据库获取数据并填充到JasperReport模板,生成HTML格式的报表,并将多个报表压缩成ZIP文件供用户下载。

846





