目的:实现从前端到后台及生成报表的整个流程。
1.jsp页面
<%@page contentType="text/html; charset=UTF-8"%>
<%@ include file="/commons/taglibs.jsp"%>
<html>
<head>
<title>生成报表</title>
<script language="JavaScript" type="text/JavaScript">
function doPrintHTML(id)
{
window.open("${ctx}/expense/expTrack.do?method=doPrintHTML&id="+id);
}
function doPrintPDF(id)
{
window.open("${ctx}/expense/expTrack.do?method=doPrintPDF&id="+id);
}
</script>
</head>
<div align=center>
<ec:table items="explist" var="exp"
action="${ctx}/expense/expTrack.do"
imagePath="${ctx}/widgets/extremecomponents/images/newHR/*.gif"
retrieveRowsCallback="limit" view="newHr">
<ec:row highlightClass="newHrECRowHighlightClass">
<ec:column property="null" title="打印明细" sortable="false"
viewsAllowed="newHr">
<a href="javascript:doGetExpItem('${exp.id}');"
style="TEXT-DECORATION: none"><img
src="${ctx}/styles/newHR/images/detail2.gif" alt="明细html详情"
border="0"> </a>
<a href="javascript:doPrintPDF('${exp.id}');"
style="TEXT-DECORATION: none"><img
src="${ctx}/styles/newHR/images/print.gif" alt="明细PDF详情"
border="0"> </a>
</ec:column>
</ec:row>
</ec:table>
</div>
</div>
</body>
</html>
2.Struts中action 中的代码编写
打印pdf的
public ActionForward doPrintPDF(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
try
{
String empName = "name";
Float totalAmountTemp =780;
//数据转换
DecimalFormat df = new DecimalFormat("0.00");
String totalAmount = df.format(totalAmountTemp);
//数据转换-End
String path = servlet.getServletContext().getRealPath("/");
path = path + "report\\image\\logo.jpg";
HashMap<String,String> parameters = new HashMap<String, String>();
parameters.put("EMPLOYEE_NAME", empName);
parameters.put("TOTAL_AMOUNT", totalAmount);
parameters.put("IMG_PATH_LOGO", path);
List<ItemsVO> resultList = itemsService.findItemByExp();
expPrintService.showPDFPage(request, response, parameters, resultList, "PteExpend");
}catch (BusinessException e) {
saveDirectlyError(request,e.getMessage());
log.error(e);
}
catch (Exception e) {
String message = "";
saveDirectlyError(request,message);
log.error(message+e);
}
return null;
}
打印html
public ActionForward doPrintPDF(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
try
{
String empName = "name";
Float totalAmountTemp =780;
//数据转换
DecimalFormat df = new DecimalFormat("0.00");
String totalAmount = df.format(totalAmountTemp);
//数据转换-End
String path = servlet.getServletContext().getRealPath("/");
path = path + "report\\image\\logo.jpg";
HashMap<String,String> parameters = new HashMap<String, String>();
parameters.put("EMPLOYEE_NAME", empName);
parameters.put("TOTAL_AMOUNT", totalAmount);
parameters.put("IMG_PATH_LOGO", path);
List<ItemsVO> resultList = itemsService.findItemByExp();
expPrintService.showHTMLPage(request, response, parameters, resultList, "PteExpend");
}catch (BusinessException e) {
saveDirectlyError(request,e.getMessage());
log.error(e);
}
catch (Exception e) {
String message = "";
saveDirectlyError(request,message);
log.error(message+e);
}
return null;
}
调用的子方法
@SuppressWarnings("deprecation")
public void showPDFPage(HttpServletRequest request, HttpServletResponse response,
Map<String, String> parameters, List<?> resultList, String reportModuleName) throws IOException{
try
{
File reportFile = new File(request.getRealPath("/report/" + reportModuleName +".jasper"));
JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(resultList);
String reportFilePath = reportFile.getPath();
JasperPrint jasperPrint;
jasperPrint = JasperFillManager.fillReport(reportFilePath, parameters, ds);
byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
//设置文件格式
response.setContentType("application/pdf");
response.setHeader("Content-disposition","attachment; filename="+reportModuleName+".pdf");
//设置文件内容大小
response.setContentLength(bytes.length);
response.setCharacterEncoding("UTF-8");
//获取输出流
ServletOutputStream ouputStream = response.getOutputStream();
//打印输出流
ouputStream.write(bytes, 0, bytes.length);
//刷新输出流
ouputStream.flush();
//关闭输出流
ouputStream.close();
} catch (JRException jre) {
System.out.println("JRException:" + jre.getMessage());
jre.printStackTrace();
}
}
html 子方法
@SuppressWarnings("deprecation")
public void showHTMLPage(HttpServletRequest request, HttpServletResponse response,
Map<String, String> parameters, List<?> resultList, String reportModuleName) throws IOException
{
try
{
//页面格式编码设置
response.setContentType("text/html;charset=UTF-8");
//定义文件操作(读写)类
PrintWriter out = response.getWriter();
//根据报表文件的物理路径绘制报表文件
File reportFile = new File(request.getRealPath("/report/"+reportModuleName+".jasper"));
String reportFilePath = reportFile.getPath();
JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(resultList);
JasperPrint jasperPrint;
jasperPrint = JasperFillManager.fillReport(reportFilePath, parameters, ds);
/**JasperRunManager.runReportToHtmlFile(reportFilePath, parameters, conn); 生成静态HTML页面到*.jsper同目录文件下**/
//JRXxxExporter:这是一系列的文件导出器,他们用于将*.jrprint 文件导出成对应格式的报表文件
//使用JRHtmlExproter导出Html格式, Xls格式的导出器 JRXlsAbstractExport
JRHtmlExporter exporter = new JRHtmlExporter();
//图片路径
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,request.getContextPath()+"\\report\\image\\");
request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,jasperPrint);
//填充导出器的相关参数
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_WRITER,out);
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,Boolean.TRUE);
//导出
exporter.exportReport();
out.close();
} catch (JRException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
把报表的模板生成好,放到相应的路径下就OK了。