소스 검색

支持导出为xls格式

sunyj 9 년 전
부모
커밋
8190c63faf

+ 11 - 2
pom.xml

@@ -15,6 +15,9 @@
 		<servlet.version>3.0-alpha-1</servlet.version>
 		<commons.dbcp.version>1.4</commons.dbcp.version>
 		<druid.version>1.0.24</druid.version>
+		<jasperreports.version>6.3.0</jasperreports.version>
+		<groovy.version>2.4.7</groovy.version>
+		<poi.version>3.10.1</poi.version>
 	</properties>
 
 	<dependencies>
@@ -62,12 +65,18 @@
 		<dependency>
 			<groupId>net.sf.jasperreports</groupId>
 			<artifactId>jasperreports</artifactId>
-			<version>6.3.0</version>
+			<version>${jasperreports.version}</version>
 		</dependency>
 		<dependency>
 			<groupId>org.codehaus.groovy</groupId>
 			<artifactId>groovy-all</artifactId>
-			<version>2.4.7</version>
+			<version>${groovy.version}</version>
+		</dependency>
+		<!-- 导出xls报表 -->
+		<dependency>
+			<groupId>org.apache.poi</groupId>
+			<artifactId>poi</artifactId>
+			<version>${poi.version}</version>
 		</dependency>
 
 		<!-- 自制中文字体 - 微软雅黑 -->

+ 37 - 17
src/main/java/com/uas/report/controller/PrintController.java

@@ -1,13 +1,14 @@
 package com.uas.report.controller;
 
+import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.util.HashMap;
 import java.util.Map;
 
+import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
-import org.apache.commons.lang.ArrayUtils;
 import org.apache.log4j.Logger;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
@@ -44,13 +45,15 @@ public class PrintController {
 	 *            可为null;where之后的条件(包括where)
 	 * @param otherParameters
 	 *            若模板已指定需要的参数,则不可为null;其他参数,区别于whereCondition,报表某些字段的值取决于这些参数
+	 * @param exportFileType
+	 *            报表打印的格式,默认为pdf
 	 * @param response
 	 * @return
 	 */
 	@RequestMapping
 	@ResponseBody
 	public String print(String userName, String reportName, String whereCondition, Map<String, Object> otherParameters,
-			HttpServletResponse response) {
+			String exportFileType, HttpServletResponse response) {
 		String message = "";
 		if (StringUtils.isEmpty(userName)) {
 			message = "未传入当前账套用户名!";
@@ -64,18 +67,14 @@ public class PrintController {
 		}
 
 		logger.info("开始打印报表: " + reportName);
-		byte[] results = printService.print(userName, reportName, whereCondition, otherParameters);
-		if (ArrayUtils.isEmpty(results)) {
-			message = "报表 " + reportName + " 打印失败!";
-			logger.error(message);
-			return message;
+		if (StringUtils.isEmpty(exportFileType)) {
+			exportFileType = "pdf";
 		}
 
-		OutputStream outputStream = null;
 		try {
-			response.setContentType("application/pdf");
-			outputStream = response.getOutputStream();
-			outputStream.write(results);
+			response.setHeader("Content-Disposition", "attachment;filename=" + reportName + "." + exportFileType);
+			OutputStream outputStream = response.getOutputStream();
+			printService.print(userName, reportName, whereCondition, otherParameters, exportFileType, outputStream);
 			outputStream.flush();
 			outputStream.close();
 		} catch (IOException e) {
@@ -105,7 +104,8 @@ public class PrintController {
 		String whereCondition = "where pu_code = 'YFMP160600001'";
 		Map<String, Object> otherParameters = new HashMap<>();
 		otherParameters.put("OTHER_PARAMETER_TEST", "天气真好!");
-		return print(userName, reportName, whereCondition, otherParameters, response);
+		String exportFileType = "xls";
+		return print(userName, reportName, whereCondition, otherParameters, exportFileType, response);
 	}
 
 	/**
@@ -119,13 +119,33 @@ public class PrintController {
 	 *            可为null;where之后的条件(包括where)
 	 * @param otherParameters
 	 *            若模板已指定需要的参数,则不可为null;其他参数,区别于whereCondition,报表某些字段的值取决于这些参数
-	 * @param response
+	 * @param request
 	 * @return
 	 */
-	@RequestMapping(params = "type=preview")
-	public String preview(String userName, String reportName, String whereCondition, Map<String, Object> otherParameters,
-			HttpServletResponse response) {
+	@RequestMapping(value = "/preview")
+	public String preview(String userName, String reportName, String whereCondition,
+			Map<String, Object> otherParameters, HttpServletRequest request) {
 		// TODO
-		return "preview.jsp";
+		String message = "";
+		if (StringUtils.isEmpty(userName)) {
+			message = "未传入当前账套用户名!";
+			logger.error(message);
+			return message;
+		}
+		if (StringUtils.isEmpty(reportName)) {
+			message = "报表名称无效!";
+			logger.error(message);
+			return message;
+		}
+
+		logger.info("开始打印报表: " + reportName);
+		String exportFileType = "pdf";
+		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+		printService.print(userName, reportName, whereCondition, otherParameters, exportFileType, outputStream);
+		request.setAttribute("data", outputStream.toByteArray());
+		request.setAttribute("message", "test");
+		message = "报表 " + reportName + " 打印完成!";
+		logger.info(message);
+		return "preview";
 	}
 }

+ 7 - 2
src/main/java/com/uas/report/service/PrintService.java

@@ -1,5 +1,6 @@
 package com.uas.report.service;
 
+import java.io.OutputStream;
 import java.util.Map;
 
 /**
@@ -21,7 +22,11 @@ public interface PrintService {
 	 *            可为null;where之后的条件(包括where)
 	 * @param otherParameters
 	 *            若模板已指定需要的参数,则不可为null;其他参数,区别于whereCondition,报表某些字段的值取决于这些参数
-	 * @return 导出的文件的字节数组
+	 * @param exportFileType
+	 *            报表打印的格式,默认为pdf
+	 * @param outputStream
+	 *            输出流
 	 */
-	public byte[] print(String userName, String reportName, String whereCondition, Map<String, Object> otherParameters);
+	public void print(String userName, String reportName, String whereCondition, Map<String, Object> otherParameters,
+			String exportFileType, OutputStream outputStream);
 }

+ 70 - 10
src/main/java/com/uas/report/service/impl/PrintServiceImpl.java

@@ -1,6 +1,7 @@
 package com.uas.report.service.impl;
 
 import java.io.File;
+import java.io.OutputStream;
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
@@ -24,9 +25,16 @@ import com.uas.report.util.ReportConstants;
 
 import net.sf.jasperreports.engine.JRException;
 import net.sf.jasperreports.engine.JasperCompileManager;
-import net.sf.jasperreports.engine.JasperRunManager;
+import net.sf.jasperreports.engine.JasperExportManager;
+import net.sf.jasperreports.engine.JasperFillManager;
+import net.sf.jasperreports.engine.JasperPrint;
 import net.sf.jasperreports.engine.design.JasperDesign;
+import net.sf.jasperreports.engine.export.JRXlsExporter;
 import net.sf.jasperreports.engine.xml.JRXmlLoader;
+import net.sf.jasperreports.export.ExporterInput;
+import net.sf.jasperreports.export.OutputStreamExporterOutput;
+import net.sf.jasperreports.export.SimpleExporterInput;
+import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
 
 /**
  * 报表打印
@@ -40,11 +48,10 @@ public class PrintServiceImpl implements PrintService {
 	private static Logger logger = Logger.getLogger(PrintService.class);
 
 	@Override
-	public byte[] print(String userName, String reportName, String whereCondition,
-			Map<String, Object> otherParameters) {
-		byte[] results = null;
+	public void print(String userName, String reportName, String whereCondition, Map<String, Object> otherParameters,
+			String exportFileType, OutputStream outputStream) {
 		if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(reportName)) {
-			return results;
+			return;
 		}
 
 		// 报表路径为报表根路径REPORT_DIR + 当前账套用户名userName
@@ -57,7 +64,7 @@ public class PrintServiceImpl implements PrintService {
 		// 报表模板不存在
 		if (!jrxmlFile.exists()) {
 			logger.error("未发现模板文件: " + jrxmlFile.getPath());
-			return results;
+			return;
 		}
 
 		String jasperFilePath = jrxmlFile.getPath().replace(".jrxml", ".jasper");
@@ -92,20 +99,25 @@ public class PrintServiceImpl implements PrintService {
 		}
 
 		try {
+			// 获取数据源
 			DataSource dataSource = getDataSource(userName);
 			if (dataSource == null) {
-				return null;
+				return;
 			}
 			Connection connection = dataSource.getConnection();
-			// 打印报表,以字节数组形式导出pdf
-			results = JasperRunManager.runReportToPdf(jasperFilePath, parameters, connection);
+
+			// 从数据库获取数据填充报表
+			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperFilePath, parameters, connection);
+			boolean exportCompleted = exportReport(jasperPrint, exportFileType, outputStream);
+			if (!exportCompleted) {
+				logger.error("报表打印失败!");
+			}
 			connection.close();
 		} catch (SQLException e) {
 			logger.error("数据库连接错误!");
 		} catch (JRException e) {
 			e.printStackTrace();
 		}
-		return results;
 	}
 
 	/**
@@ -177,6 +189,54 @@ public class PrintServiceImpl implements PrintService {
 			// defaultDataSource.close();
 		}
 		return null;
+	}
 
+	/**
+	 * 以不同的格式打印报表
+	 * 
+	 * @param jasperPrint
+	 * @param exportFileType
+	 * @param outputStream
+	 * @return 报表是否成功打印
+	 */
+	private boolean exportReport(JasperPrint jasperPrint, String exportFileType, OutputStream outputStream) {
+		try {
+			if (exportFileType.equals("pdf")) {
+				exportReportToPdf(jasperPrint, outputStream);
+			} else if (exportFileType.equals("xls")) {
+				exportReportToXls(jasperPrint, outputStream);
+			}
+		} catch (JRException e) {
+			e.printStackTrace();
+			return false;
+		}
+		return true;
+	}
+
+	/**
+	 * 以pdf的格式打印报表
+	 * 
+	 * @param jasperPrint
+	 * @param outputStream
+	 * @throws JRException
+	 */
+	private void exportReportToPdf(JasperPrint jasperPrint, OutputStream outputStream) throws JRException {
+		JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
+	}
+
+	/**
+	 * 以xls的格式打印报表
+	 * 
+	 * @param jasperPrint
+	 * @param outputStream
+	 * @throws JRException
+	 */
+	private void exportReportToXls(JasperPrint jasperPrint, OutputStream outputStream) throws JRException {
+		JRXlsExporter exporter = new JRXlsExporter();
+		ExporterInput exporterInput = new SimpleExporterInput(jasperPrint);
+		exporter.setExporterInput(exporterInput);
+		OutputStreamExporterOutput exporterOutput = new SimpleOutputStreamExporterOutput(outputStream);
+		exporter.setExporterOutput(exporterOutput);
+		exporter.exportReport();
 	}
 }

+ 2 - 2
src/main/java/com/uas/report/util/ReportConstants.java

@@ -12,8 +12,8 @@ public class ReportConstants {
 	/**
 	 * 报表根路径
 	 */
-//	public static final String REPORT_DIR = PathUtils.getFilePath() + "reports" + File.separator;
-	 public static final String REPORT_DIR = "/data/reports" + File.separator;
+	public static final String REPORT_DIR = PathUtils.getFilePath() + "reports" + File.separator;
+//	 public static final String REPORT_DIR = "/data/reports" + File.separator;
 
 	/**
 	 * 报表参数 - WHERE_CONDITION,where字句(需含where)

+ 0 - 5
src/main/webapp/WEB-INF/views/index.html

@@ -1,5 +0,0 @@
-<html>
-<body>
-<h2>你好Hello World!</h2>
-</body>
-</html>

+ 7 - 0
src/main/webapp/WEB-INF/views/index.jsp

@@ -0,0 +1,7 @@
+<%@ page language="java" contentType="text/html; UTF-8"
+	pageEncoding="UTF-8"%>
+<html>
+<body>
+	<h2>你好Hello World!</h2>
+</body>
+</html>

+ 24 - 0
src/main/webapp/WEB-INF/views/preview.jsp

@@ -0,0 +1,24 @@
+<%@ page language="java" contentType="text/html; UTF-8"
+	pageEncoding="UTF-8"%>
+<%@ page language="java" import="java.io.IOException"%>
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+<title>Preview</title>
+<%
+	byte[] data = (byte[]) request.getAttribute("data");
+%>
+
+</head>
+<body>
+	<%
+		response.reset();
+		response.setContentType("application/pdf");
+		response.getOutputStream().write(data);
+		out.clear();
+		out = pageContext.pushBody();
+	%>
+	}
+</body>
+</html>

+ 1 - 1
src/main/webapp/WEB-INF/webmvc.xml

@@ -23,7 +23,7 @@
 	<bean
 		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 		<property name="prefix" value="/WEB-INF/views/" />
-		<property name="suffix" value=".html" />
+		<property name="suffix" value=".jsp" />
 		<property name="contentType" value="text/html;charset=UTF-8" />
 	</bean>