浏览 3994 次
该帖已经被评为隐藏帖
|
|
---|---|
作者 | 正文 |
发表时间:2009-08-18
本文是结合我工作中实际项目来写的,所以有部分内容与你们将要使用的有所不同。 先介绍下我的项目,此项目为flex+java开发的,中间flex使用了自己写的一个小型框架来实现。
此报表导出实现了多表头打印,个人感觉应用还是比较理想的。
先来点核心代码:
package com.wfy.util; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.HashPrintServiceAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.PrintServiceAttributeSet; import javax.print.attribute.standard.Copies; import javax.print.attribute.standard.MediaSizeName; import javax.print.attribute.standard.PrinterName; import javax.swing.GroupLayout.Alignment; import net.sf.jasperreports.engine.JRBand; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JRReport; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperExportManager; 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.base.JRBaseLine; import net.sf.jasperreports.engine.base.JRBasePrintText; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import net.sf.jasperreports.engine.design.JRDesignBand; import net.sf.jasperreports.engine.design.JRDesignExpression; import net.sf.jasperreports.engine.design.JRDesignField; import net.sf.jasperreports.engine.design.JRDesignStaticText; import net.sf.jasperreports.engine.design.JRDesignTextField; import net.sf.jasperreports.engine.design.JasperDesign; import net.sf.jasperreports.engine.export.JRHtmlExporter; import net.sf.jasperreports.engine.export.JRHtmlExporterParameter; import net.sf.jasperreports.engine.export.JRPrintServiceExporter; import net.sf.jasperreports.engine.export.JRPrintServiceExporterParameter; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.export.JRXlsExporterParameter; import net.sf.jasperreports.engine.util.JRSaver; import net.sf.jasperreports.view.JasperViewer; import org.apache.commons.beanutils.BasicDynaBean; import org.apache.commons.beanutils.BasicDynaClass; import org.apache.commons.beanutils.DynaBean; import org.apache.commons.beanutils.DynaProperty; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jaspersoft.ireport.designer.sheet.properties.HorizontalAlignmentProperty; import com.wfy.servlet.StartServlet; /** * JasperReport 動態列 打印 * * @author hxy * */ public class ReportProcess { private static Log logger = LogFactory.getLog(Copy_2_of_ReportProcess.class); /** 設置字段寬度 */ // private final static int textWidth = 80; /** 設置字段高度 */ private final static int textHeight = 20; /** coulumnHeader區域字體大小 */ private final static int columnHeaderfontSize = 11; /** detail 區域字體大小 */ private final static int fontSize = 9; /** 設置間距 */ // private final static int X = 0; /** coulumnHeader區域高度 */ private final static int columnHeaderHeight = 20; /** detail 區域高度 */ private final static int detailHeight = 20; /** */ private static String aliasColumn = "column"; private static double mm_Pixel = 2.83; public static int mmToPixel(int mm){ return (int)Math.rint((mm * mm_Pixel)); } public String createReport(Map pageSet, String title, List coluns, List list, String reportType){ String url1 = "createPdf\\"+TimeUtil.dateTime6()+"."+reportType; String url = StartServlet.webRoot+url1; FileUtil.createFolder(url); File f = new File(url); try { OutputStream out = new FileOutputStream(f); preview(pageSet, title, coluns, list, out, reportType); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } url1 = url1.replace("\\", "/"); return url1; } /** * PDF打印 * * @param headers * colimnHeaders * @param list * 數據來源 * @param out * 輸出流 * @throws Exception */ public void preview(Map pageSet, String titleStr, List coluns, List<Map> list, OutputStream out, String reportType) throws Exception { long start = System.currentTimeMillis(); JasperReport jp = getJasperReport(pageSet, titleStr, coluns, reportType); Map<String, Object> parameters = new HashMap<String, Object>(); JasperPrint jasperPrint = JasperFillManager.fillReport(jp, parameters, new JRBeanCollectionDataSource(getBaseList(alias, list)));//phrase(list) logger.info("Filling time : " + (System.currentTimeMillis() - start)); //将解析完的参数传入报表模板中并生成报表 if(reportType.equals("pdf")){ JasperExportManager.exportReportToPdfStream(jasperPrint, out); }else if(reportType.equals("xls")){ JRXlsExporter exporter = new JRXlsExporter(); ByteArrayOutputStream oStream = new ByteArrayOutputStream(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, oStream); 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(); byte[] bytes = oStream.toByteArray(); out.write(bytes); }else{ //生成html JRHtmlExporter exporter = new JRHtmlExporter(); ByteArrayOutputStream oStream = new ByteArrayOutputStream(); exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE); exporter.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRHtmlExporterParameter.CHARACTER_ENCODING, "utf-8"); exporter.setParameter(JRHtmlExporterParameter.OUTPUT_STREAM, oStream); exporter.exportReport(); byte[] bytes = oStream.toByteArray(); out.write(bytes); } logger.info("Printing time : " + (System.currentTimeMillis() - start)); } public List<String[]> phrase(List<Object[]> list) { List<String[]> temps = new ArrayList<String[]>(); String[] s = null; for (Object[] obj : list) { s = new String[obj.length]; for (int i = 0; i < obj.length; i++) { s[i] = obj[i].toString(); } temps.add(s); } return temps; } /** * 產生columnHeaders的別名(Headers[]有可能為中文,所以有必要用別名來替換) * * @param headers * @return */ private String[] preaseAliasColumnHeaders(String headers[]) { int size = headers.length; String[] alias = new String[size]; for (int i = 0; i < size; i++) { alias[i] = aliasColumn + i; } return alias; } /** * 產生Template文件 * * @param headers * @param alias * @return * @throws JRException */ private List colunsMode = new ArrayList(); private double scaling = 1.00; private List<Integer> widths = new ArrayList(); private JRDesignBand columnHeader = null; private int X = 0; private int Y = 0; List<String> alias = new ArrayList(); @SuppressWarnings("deprecation") private JasperReport getJasperReport(Map pageSet, String titleStr, List coluns, String reportType) throws JRException { JasperDesign design = new JasperDesign(); // name="statistics" design.setName("富友erp数据导出"); // columnSpacing="0" design.setColumnSpacing(0); // leftMargin="30" design.setLeftMargin(0); // rightMargin="30" design.setRightMargin(0); // topMargin="20" design.setTopMargin(0); // bottomMargin="20" design.setBottomMargin(0); design.setIgnorePagination(true); //up down left rigth pageWidth pageHeigth layout(V(竖版),H(横板)) int up = mmToPixel(Integer.parseInt(pageSet.get("up").toString())); int down = mmToPixel(Integer.parseInt(pageSet.get("down").toString())); int left = mmToPixel(Integer.parseInt(pageSet.get("left").toString())); int right = mmToPixel(Integer.parseInt(pageSet.get("right").toString())); int pageWidth = mmToPixel(Integer.parseInt(pageSet.get("pageWidth").toString())); int pageHeight = mmToPixel(Integer.parseInt(pageSet.get("pageHeight").toString())); String layout = pageSet.get("layout").toString(); int tableWidth = 0; for (int i = 0; i < coluns.size(); i++) { Map map = (Map)coluns.get(i); tableWidth += Integer.parseInt(map.get("width").toString()); } if(reportType.equals("pdf")){ // columnCount="1" // printOrder="Vertical" design.setPrintOrder(JRReport.PRINT_ORDER_VERTICAL); // orientation="Portrait" design.setOrientation(JRReport.ORIENTATION_PORTRAIT); // pageWidth="595" //缩放值 if(layout.equals("V")){ scaling = (double)(pageWidth-left-right)/(double)tableWidth; design.setPageHeight(pageHeight); design.setPageWidth(pageWidth); design.setColumnWidth(pageWidth-left-right); }else{ scaling = (double)(pageHeight-left-right)/(double)tableWidth; design.setPageHeight(pageWidth); design.setPageWidth(pageHeight); design.setColumnWidth(pageHeight-left-right); } // leftMargin="30" design.setLeftMargin(left); // rightMargin="30" design.setRightMargin(right); // topMargin="20" design.setTopMargin(up); // bottomMargin="20" design.setBottomMargin(down); // whenNoDataType="NoPages" design.setIgnorePagination(false); design.setWhenNoDataType(JRReport.WHEN_NO_DATA_TYPE_BLANK_PAGE); // isTitleNewPage="false" design.setTitleNewPage(false); // isSummaryNewPage="false" design.setSummaryNewPage(false); } JRDesignBand title = new JRDesignBand(); title.setHeight(50); JRDesignStaticText titleText = new JRDesignStaticText(); titleText.setText(titleStr); titleText.setX(0); titleText.setFontSize(20); titleText.setHeight(40); titleText.setWidth( (int)Math.rint(tableWidth*scaling) ); titleText.setTextAlignment(JRDesignStaticText.HORIZONTAL_ALIGN_CENTER); titleText.setPdfFontName("STSong-Light"); titleText.setPdfEmbedded(true); titleText.setPdfEncoding("UniGB-UCS2-H"); title.addElement(titleText); design.setTitle(title); columnHeader = new JRDesignBand(); this.ergodicColumns(coluns, X, 0); columnHeader.setHeight(columnHeaderHeight*(RowLength+1)); X = 0; Y = 0; JRDesignBand detail = new JRDesignBand(); detail.setHeight(detailHeight); for (int j = 0; j < alias.size(); j++) { // define fields JRDesignField field = new JRDesignField(); field.setName( alias.get(j) ); field.setValueClass(String.class); design.addField(field); // add text fields for displaying fields JRDesignTextField textField = new JRDesignTextField(); JRDesignExpression expression = new JRDesignExpression(); expression.setText("$F{" + alias.get(j) + "}"); expression.setValueClass(String.class); textField.setExpression(expression); textField.setFontSize(fontSize); textField.setHeight(textHeight); textField.setWidth(widths.get(j)); textField.setX(X); textField.setPdfFontName("STSong-Light"); textField.setPdfEmbedded(true); textField.setPdfEncoding("UniGB-UCS2-H"); textField.setHorizontalAlignment(JRBasePrintText.HORIZONTAL_ALIGN_CENTER); textField.setVerticalAlignment(JRBasePrintText.VERTICAL_ALIGN_MIDDLE); textField.setLeftBorder(JRBaseLine.PEN_1_POINT); textField.setTopBorder(JRBaseLine.PEN_1_POINT); textField.setRightBorder(JRBaseLine.PEN_1_POINT); textField.setBottomBorder(JRBaseLine.PEN_1_POINT); textField.setBlankWhenNull(true); detail.addElement(textField); X += widths.get(j); } design.setColumnHeader(columnHeader); design.setDetail(detail); if(reportType.equals("pdf")){ JRDesignBand pageFooter = new JRDesignBand(); pageFooter.setHeight(20); JRDesignTextField footerText = new JRDesignTextField(); JRDesignExpression expressionF = new JRDesignExpression(); expressionF.setText("$V{PAGE_NUMBER}"); expressionF.setValueClass(Integer.class); footerText.setExpression(expressionF); if(layout.equals("V")){ footerText.setX(pageWidth-right-100); }else{ footerText.setX(pageHeight-right-100); } footerText.setFontSize(9); footerText.setHeight(15); footerText.setWidth(100); footerText.setPdfFontName("STSong-Light"); footerText.setPdfEmbedded(true); footerText.setPdfEncoding("UniGB-UCS2-H"); pageFooter.addElement(footerText); design.setPageFooter(pageFooter); } return JasperCompileManager.compileReport(design); } private int RowLength = 0; private List ergodicColumns(List array, int X, int rowLength) { if(rowLength>=RowLength){ RowLength = rowLength; } List arrayC = new ArrayList(); int w = 0; /** * 需要得到所有表头信息。 * 如果为多级表头时,需要得到每级的表头信息,并记录其信息。 * **/ for(int i = 0; i<array.size(); i++){ //创建表头信息 Map map = (Map)array.get(i); int width = (int)Math.rint((Double.parseDouble(map.get("width").toString()))*scaling); // add column headers JRDesignStaticText staticText = new JRDesignStaticText(); staticText.setText(map.get("title").toString()); staticText.setFontSize(columnHeaderfontSize); staticText.setHeight( (Integer.parseInt(map.get("length").toString())+1)*textHeight ); staticText.setWidth(width); staticText.setX(X); staticText.setY(rowLength*columnHeaderHeight); staticText.setPdfFontName("STSong-Light"); staticText.setPdfEmbedded(true); staticText.setPdfEncoding("UniGB-UCS2-H"); staticText.setHorizontalAlignment(JRBasePrintText.HORIZONTAL_ALIGN_CENTER); staticText.setVerticalAlignment(JRBasePrintText.VERTICAL_ALIGN_MIDDLE); staticText.setLeftBorder(JRBaseLine.PEN_1_POINT); staticText.setTopBorder(JRBaseLine.PEN_1_POINT); staticText.setRightBorder(JRBaseLine.PEN_1_POINT); staticText.setBottomBorder(JRBaseLine.PEN_1_POINT); columnHeader.addElement(staticText); if(map.get("array")==null){ colunsMode.add(map); alias.add(map.get("name").toString()); this.widths.add(width); w = width; arrayC.add(staticText); }else{ Object[] obj = (Object[])map.get("array"); List lista = new ArrayList(); for (int j = 0; j < obj.length; j++) { lista.add(obj[j]); } List list = this.ergodicColumns(lista, X, rowLength+1 ); /* * 根据X坐标重新计算 每列位置。 * */ staticText.setX(X); int xa = X; w = 0; for (int j = 0; j < list.size(); j++) { JRDesignStaticText staticTextA = (JRDesignStaticText)list.get(j); staticTextA.setX(xa); xa = xa + staticTextA.getWidth(); w += staticTextA.getWidth(); } if(w!=0){ staticText.setWidth(w); }else{ w = staticText.getWidth(); } } X += w; } return arrayC; } /** * 利用反射機制,裝拼數據 * * @param headers * @param list * @return * @throws Exception */ private List<Object> getBaseList(List<String> headers, List<Map> list) throws Exception { List<Object> result = new ArrayList<Object>(); int length = headers.size(); DynaProperty[] dynaProps = new DynaProperty[length]; for (int i = 0; i < length; i++) { dynaProps[i] = new DynaProperty(headers.get(i), String.class); } BasicDynaClass dynaClass = new BasicDynaClass("first", BasicDynaBean.class, dynaProps); for (Map obj : list) { DynaBean employee = dynaClass.newInstance(); for (int i = 0; i < length; i++) { employee.set(headers.get(i), obj.get(headers.get(i))); } result.add(employee); } return result; } }
此部分为此函数的核心代码,需要使用的时候需要调用 createReport 方法来执行。
createReport(Map pageSet, String title, List coluns, List list, String reportType) 传入参数:pageSet纸张部分设定 //up down left rigth pageWidth pageHeigth layout(V(竖版),H(横板)) int up = mmToPixel(Integer.parseInt(pageSet.get("up").toString())); int down = mmToPixel(Integer.parseInt(pageSet.get("down").toString())); int left = mmToPixel(Integer.parseInt(pageSet.get("left").toString())); int right = mmToPixel(Integer.parseInt(pageSet.get("right").toString())); int pageWidth = mmToPixel(Integer.parseInt(pageSet.get("pageWidth").toString())); int pageHeight = mmToPixel(Integer.parseInt(pageSet.get("pageHeight").toString())); String layout = pageSet.get("layout").toString();
title 打印的标题,如有必要可以进行相应的扩展 coluns 打印的表头数据 colums结构如下: obj["name"] = 名称obj["title"] = 标题 obj["width"] = 表格宽度 obj["length"] = 如果为多表头的时候有效,设置此表头占用高度 obj["array"] = 如果为多表头,将其子表头信息填入(为List) obj为Map类型
reportType 导出文件的格式 pdf , xls , html 三种文件格式
组合完毕后,既能导出相应的文件出来了。
下面是结合flex 来创建 上述条件
package com.wfy.sa.basic.report { import com.wfy.components.advancedDataGrid.advancedDataGridClasses.AdvancedDataGridColumnGroup; import com.wfy.components.commandmanage.ICommand; import com.wfy.components.datagridext.DataGridColumnExt; import com.wfy.components.datagridext.DataGridExt; import flash.external.ExternalInterface; import mx.rpc.events.ResultEvent; import mx.rpc.remoting.RemoteObject; public class PrintReportByDataGridCommand implements ICommand { private var dataGrid:DataGridExt private var title:String; private var remoteObject:Object; private var pageSet:PageSet; public function PrintReportByDataGridCommand(pageSet:PageSet, title:String, dataGrid:DataGridExt)//DataGridExt 对 AdvancedDataGrid进行扩展,与我们没关系 { this.title = title; this.pageSet = pageSet; this.dataGrid = dataGrid; this.remoteObject = new RemoteObject("UtilFunctionService"); } private var colunsMode:Array = new Array(); public function execute():void { // var array:Array = this.dataGrid.columns;//.getDataGridStyleAS().getColumns(); var array:Array = this.dataGrid.groupedColumns; var coluns:Array = new Array(); coluns = this.ergodicColumns(array, 0); //遍历表格高度。 coluns = this.getRowLengthColumns(coluns, 0); var list:Array = new Array(); var length:int = this.dataGrid.getRowsLength(); for(var j:int=0; j<length; j++){ var obj:Object = new Object(); for(var k:int=0; k<colunsMode.length; k++){ obj[colunsMode[k]["name"]] = this.dataGrid.getLabel(j , colunsMode[k]["name"]); } list.push(obj); } remoteObject.createReportByDataGrid(pageSet, coluns, this.title, list, "pdf"); } public function OnResult(resultEvent:ResultEvent):String { var reportUrl:String = resultEvent.result.toString(); ExternalInterface.call("window.open", "../"+reportUrl , "打印", "top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=yes, location=no, status=no", "_blank"); return ""; } private function getRowLengthColumns(array:Array, rowlength:int):Array { for(var i:int=0; i<array.length; i++){ if(array[i]["array"]!=null){ var arrayI:Array = this.getRowLengthColumns(array[i]["array"], rowlength+1); // arrayI[i]["length"] = RowLength-rowlength-1; array[i]["array"] = arrayI; array[i]["length"] = RowLength-rowlength-1; }else{ array[i]["length"] = RowLength-rowlength; } } return array; } private var RowLength:int = 0; private function ergodicColumns(array:Array, rowlength:int):Array { if(rowlength>=RowLength){ RowLength = rowlength; } var arrayC:Array = new Array(); /** * 需要得到所有表头信息。 * 如果为多级表头时,需要得到每级的表头信息,并记录其信息。 * **/ for(var i:int=0; i<array.length; i++){ if(array[i] is AdvancedDataGridColumnGroup){ var ad:AdvancedDataGridColumnGroup = array[i] as AdvancedDataGridColumnGroup; if(ad.visible){ // if(ad.headerText!=null && ad.headerText!=""){ var obj:Object = new Object(); obj["name"] = ad.dataField; obj["title"] = ad.headerText; obj["width"] = ad.width; obj["array"] = this.ergodicColumns(ad.children, rowlength+1 ); arrayC.push(obj); } }else if(array[i] is DataGridColumnExt){ var da:DataGridColumnExt = array[i] as DataGridColumnExt; if(da.visible){ if(da.dataField!=null && da.dataField!="" && da.headerText!=null && da.headerText!=""){ var obj:Object = new Object(); obj["name"] = da.dataField; obj["title"] = da.headerText; obj["width"] = da.width;//可能需要重新计算 arrayC.push(obj); colunsMode.push(obj); } } } } return arrayC; } } }
此函数是我们在flex中做的操作,根据flex的datagrid得到打印的信息,以及表头信息。并传送给后台生成打印文件。
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2009-08-19
建议楼主可以把效果截图发上来,再附上代码。
|
|
返回顶楼 | |
发表时间:2009-08-20
云中苍月 写道 建议楼主可以把效果截图发上来,再附上代码。
代码上述已经包含了,别的也没什么代码了。 效果图其实也就是表格输出。 |
|
返回顶楼 | |
发表时间:2009-08-21
转我原创贴中的大量代码,没注明出处~~~
楼主注意一下~ 我公司是台湾(inqgen)的分公司,所以才用的繁体字, @author hxy 连我的名称和注解字体的没做修改,哎~ 太不厚道了~ http://wingware.iteye.com/blog/286295 |
|
返回顶楼 | |