JasperReport和iReport是不错的Java报表工具. 在实际项目中, 本人用它们开发了20个Report, 涉及SubReport, Image, Graph, 积累了一些经验. 尤其是关于Export到Excel方面, 文档上也很少提及, 纯粹是摸索出来的, 有的问题还是通过读源代码才解决的. 此贴并非入门教程, 差不多算是笔记吧, 以问答形式记录.
/**
*
Title: ReportProviderServlet
Description: Servlet to generate Jasper reports
Copyright: Copyright (c) 2004
Company: *****
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.base.*;
import net.sf.jasperreports.engine.export.*;
import net.sf.jasperreports.engine.util.*;
import org.apache.log4j.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ReportProviderServlet extends HttpServlet
{
private static Logger log = LogManager.getLogger(ReportProviderServlet.class);
//Initialize: Setup DataSourceManager
public void init() throws javax.servlet.ServletException
{
String prefix = getServletContext().getRealPath("/");
String file = getInitParameter("data-source-file");
DataSourceManager.configure(prefix + file);
log.info("initialized successfully!");
}
//Process the HTTP request
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String reportClass = request.getParameter("reportClass");
log.debug("Running Report:" + reportClass);
boolean isExcelFormat = false;
if (reportClass == null)
{
throw new IllegalArgumentException("Jasper Class Unspecified");
}
String reportFormat = request.getParameter("reportFormat");
if (reportFormat == null)
{
reportFormat = "jasperPrint";
}
try
{
JasperReport myRpt = JasperManager.loadReport(this.getClass()
.getResourceAsStream("/jasperReports/" +
reportClass + ".jasper"));
//set ReprintHeaderOnEachPage=false for Excel Format
isExcelFormat = reportFormat.equalsIgnoreCase("excel");
if (isExcelFormat)
{
//use reflect to set the private field of JRBaseReport
//No margin for excel format, max pageHeight
java.lang.reflect.Field margin = JRBaseReport.class.getDeclaredField(
"leftMargin");
margin.setAccessible(true);
margin.setInt(myRpt, 0);
margin = JRBaseReport.class.getDeclaredField("topMargin");
margin.setAccessible(true);
margin.setInt(myRpt, 0);
margin = JRBaseReport.class.getDeclaredField("bottomMargin");
margin.setAccessible(true);
margin.setInt(myRpt, 0);
java.lang.reflect.Field pageHeight = JRBaseReport.class.getDeclaredField(
"pageHeight");
pageHeight.setAccessible(true);
pageHeight.setInt(myRpt, Integer.MAX_VALUE);
//Don't print group header on each page
if (null != myRpt.getGroups())
{
for (int i = 0; i < myRpt.getGroups().length; i++)
{
myRpt.getGroups()[i].setReprintHeaderOnEachPage(false);
}
}
}
Map params = new HashMap(10);
Enumeration enu = request.getParameterNames();
while (enu.hasMoreElements())
{
String key = (String) enu.nextElement();
params.put(key,
request.getParameter(key).toUpperCase().replaceAll("'", "''"));
log.debug(key + "=" + request.getParameter(key));
}
log.debug("Before Filling");
OutputStream httpOut = response.getOutputStream();
Connection conn = DataSourceManager.getConnection(request.getSession());
JasperPrint rptPnt = JasperManager.fillReport(myRpt, params, conn);
conn.close();
if (reportFormat.equalsIgnoreCase("jasperPrint"))
{
response.setContentType("application/octet-stream");
JRSaver.saveObject(rptPnt, httpOut);
}
else if (reportFormat.equalsIgnoreCase("pdf"))
{
response.setContentType("application/pdf");
response.setHeader("Content-Disposition",
"attachment;filename=\"" + reportClass + ".PDF\"");
JasperManager.printReportToPdfStream(rptPnt, httpOut);
}
else if (reportFormat.equalsIgnoreCase("excel"))
{
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=\"" + reportClass + ".XLS\"");
JRXlsExporter exporter = new JRXlsExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, rptPnt);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, httpOut);
exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
Boolean.TRUE);
exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
Boolean.FALSE);
exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,
Boolean.FALSE);
exporter.exportReport();
}
else if (reportFormat.equalsIgnoreCase("html"))
{
JRHtmlExporter exporter = new JRHtmlExporter();
response.setContentType("text/html");
Map imagesMap = new HashMap();
request.getSession().setAttribute("IMAGES_MAP", imagesMap);
exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP,
imagesMap);
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,
"image.jsp image=");
exporter.setParameter(JRExporterParameter.JASPER_PRINT, rptPnt);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, httpOut);
exporter.exportReport();
}
log.debug("Report Exported");
}
catch (Exception ex)
{
log.error("Error Occured", ex);
}
}
}
/**
*
Title: JRDataSourceAdapter
Description: Converting JRDataSource to Mapped ArrayList
Copyright: Copyright (c) 2004
Company: *****
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.design.*;
import java.util.*;
public class JRDataSourceAdapter
{
public static Map JRDataSource2Map(JRDataSource dataSource, String[] fieldNames,
Class[] fieldClasses) throws JRException
{
HashMap result;
if (fieldNames.length != fieldClasses.length)
{
throw new JRException("Number of Field Name & Class unmatch");
}
JRDesignField[] fields = new JRDesignField[fieldNames.length];
result = new HashMap(4);
for (int i = 0; i < fieldNames.length; i++)
{
fields[i] = new JRDesignField();
fields[i].setName(fieldNames[i]);
fields[i].setValueClass(fieldClasses[i]);
result.put(fieldNames[i], new ArrayList());
}
do
{
for (int i = 0; i < fields.length; i++)
{
Object value = dataSource.getFieldValue(fields[i]);
((ArrayList) result.get(fields[i].getName())).add(value);
}
}
while (dataSource.next());
return result;
}
}
/**
*
Title: GraphProvider
Description: Generate JFreeChart Image
Copyright: Copyright (c) 2004
Company: ****
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.design.*;
import net.sf.jasperreports.engine.export.*;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.plot.*;
import org.jfree.data.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
public class GraphProvider
{
public static Image getImage(Map dataSource, String fieldNameX, String fieldNameY,
String chartName, String titleX, String titleY, boolean isBarChart, int imageWidth,
int imageHeight) throws JRException
{
JRDesignField fieldX = new JRDesignField();
fieldX.setName(fieldNameX);
fieldX.setValueClass(java.lang.String.class);
JRDesignField fieldY = new JRDesignField();
fieldY.setName(fieldNameY);
fieldY.setValueClass(java.lang.Double.class);
ArrayList periods = (ArrayList) dataSource.get(fieldNameX);
ArrayList values = (ArrayList) dataSource.get(fieldNameY);
DefaultCategoryDataset categoryDs = new DefaultCategoryDataset();
for (int i = 0; i < values.size(); i++)
{
Object obj = values.get(i);
double dataValue = 0;
if (obj != null)
{
dataValue = ((Double) obj).doubleValue();
}
categoryDs.addValue(dataValue, null, (String) periods.get(i));
}
JFreeChart c = null;
if (isBarChart)
{
c = ChartFactory.createBarChart(chartName, titleX, titleY, categoryDs,
PlotOrientation.VERTICAL, false, false, false);
}
else
{
c = ChartFactory.createLineChart(chartName, titleX, titleY, categoryDs,
PlotOrientation.VERTICAL, false, false, false);
}
c.getTitle().setFont(new Font("Arial", Font.BOLD, 16));
NumberAxis axis = (NumberAxis) c.getCategoryPlot().getRangeAxis();
axis.setAutoRange(true);
TickUnitSource tickUnits = NumberAxis.createIntegerTickUnits();
axis.setStandardTickUnits(tickUnits);
return (c.createBufferedImage(imageWidth, imageHeight));
}
}
本文地址:http://com.8s8s.com/it/it13752.htm