转:使用jasperreport动态生成pdf,excel,html

本文是结合我工作中实际项目来写的,所以有部分内容与你们将要使用的有所不同。

先介绍下我的项目,此项目为flex+java开发的,中间flex使用了自己写的一个小型框架来实现。

 

此报表导出实现了多表头打印,个人感觉应用还是比较理想的。

 

 

先来点核心代码:

  

Java代码   收藏代码
  1. package com.wfy.util;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.File;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.OutputStream;  
  8. import java.util.ArrayList;  
  9. import java.util.HashMap;  
  10. import java.util.List;  
  11. import java.util.Map;  
  12.   
  13. import javax.print.attribute.HashPrintRequestAttributeSet;  
  14. import javax.print.attribute.HashPrintServiceAttributeSet;  
  15. import javax.print.attribute.PrintRequestAttributeSet;  
  16. import javax.print.attribute.PrintServiceAttributeSet;  
  17. import javax.print.attribute.standard.Copies;  
  18. import javax.print.attribute.standard.MediaSizeName;  
  19. import javax.print.attribute.standard.PrinterName;  
  20. import javax.swing.GroupLayout.Alignment;  
  21.   
  22. import net.sf.jasperreports.engine.JRBand;  
  23. import net.sf.jasperreports.engine.JRException;  
  24. import net.sf.jasperreports.engine.JRExporterParameter;  
  25. import net.sf.jasperreports.engine.JRReport;  
  26. import net.sf.jasperreports.engine.JasperCompileManager;  
  27. import net.sf.jasperreports.engine.JasperExportManager;  
  28. import net.sf.jasperreports.engine.JasperFillManager;  
  29. import net.sf.jasperreports.engine.JasperPrint;  
  30. import net.sf.jasperreports.engine.JasperReport;  
  31. import net.sf.jasperreports.engine.JasperRunManager;  
  32. import net.sf.jasperreports.engine.base.JRBaseLine;  
  33. import net.sf.jasperreports.engine.base.JRBasePrintText;  
  34. import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;  
  35. import net.sf.jasperreports.engine.design.JRDesignBand;  
  36. import net.sf.jasperreports.engine.design.JRDesignExpression;  
  37. import net.sf.jasperreports.engine.design.JRDesignField;  
  38. import net.sf.jasperreports.engine.design.JRDesignStaticText;  
  39. import net.sf.jasperreports.engine.design.JRDesignTextField;  
  40. import net.sf.jasperreports.engine.design.JasperDesign;  
  41. import net.sf.jasperreports.engine.export.JRHtmlExporter;  
  42. import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;  
  43. import net.sf.jasperreports.engine.export.JRPrintServiceExporter;  
  44. import net.sf.jasperreports.engine.export.JRPrintServiceExporterParameter;  
  45. import net.sf.jasperreports.engine.export.JRXlsExporter;  
  46. import net.sf.jasperreports.engine.export.JRXlsExporterParameter;  
  47. import net.sf.jasperreports.engine.util.JRSaver;  
  48. import net.sf.jasperreports.view.JasperViewer;  
  49.   
  50. import org.apache.commons.beanutils.BasicDynaBean;  
  51. import org.apache.commons.beanutils.BasicDynaClass;  
  52. import org.apache.commons.beanutils.DynaBean;  
  53. import org.apache.commons.beanutils.DynaProperty;  
  54. import org.apache.commons.logging.Log;  
  55. import org.apache.commons.logging.LogFactory;  
  56.   
  57. import com.jaspersoft.ireport.designer.sheet.properties.HorizontalAlignmentProperty;  
  58. import com.wfy.servlet.StartServlet;  
  59.   
  60. /** 
  61.  * JasperReport 動態列 打印 
  62.  *  
  63.  * @author hxy 
  64.  *  
  65.  */  
  66. public class ReportProcess {  
  67.   
  68.     private static Log logger = LogFactory.getLog(Copy_2_of_ReportProcess.class);  
  69.     /** 設置字段寬度 */  
  70. //  private final static int textWidth = 80;  
  71.     /** 設置字段高度 */  
  72.     private final static int textHeight = 20;  
  73.     /** coulumnHeader區域字體大小 */  
  74.     private final static int columnHeaderfontSize = 11;  
  75.     /** detail 區域字體大小 */  
  76.     private final static int fontSize = 9;  
  77.     /** 設置間距 */  
  78. //  private final static int X = 0;  
  79.     /** coulumnHeader區域高度 */  
  80.     private final static int columnHeaderHeight = 20;  
  81.     /** detail 區域高度 */  
  82.     private final static int detailHeight = 20;  
  83.     /**  */  
  84.     private static String aliasColumn = "column";  
  85.       
  86.     private static double mm_Pixel = 2.83;  
  87.       
  88.     public static int mmToPixel(int mm){  
  89.         return (int)Math.rint((mm * mm_Pixel));  
  90.     }  
  91.   
  92.     public  String createReport(Map pageSet, String title, List coluns, List list, String reportType){  
  93.         String url1 = "createPdf\\"+TimeUtil.dateTime6()+"."+reportType;  
  94.         String url = StartServlet.webRoot+url1;  
  95.         FileUtil.createFolder(url);  
  96.         File f = new File(url);  
  97.           
  98.         try {  
  99.             OutputStream out = new FileOutputStream(f);  
  100.             preview(pageSet, title, coluns, list, out, reportType);  
  101.             out.close();  
  102.         } catch (FileNotFoundException e) {  
  103.             e.printStackTrace();  
  104.         } catch (Exception e) {  
  105.             e.printStackTrace();  
  106.         }  
  107.   
  108.         url1 = url1.replace("\\", "/");  
  109.           
  110.         return url1;  
  111.     }  
  112.       
  113.     /** 
  114.      * PDF打印 
  115.      *  
  116.      * @param headers 
  117.      *            colimnHeaders 
  118.      * @param list 
  119.      *            數據來源 
  120.      * @param out 
  121.      *            輸出流 
  122.      * @throws Exception 
  123.      */  
  124.       
  125.     public  void preview(Map pageSet, String titleStr, List coluns, List<Map> list,  
  126.             OutputStream out, String reportType) throws Exception {  
  127.         long start = System.currentTimeMillis();  
  128.         JasperReport jp = getJasperReport(pageSet, titleStr, coluns, reportType);  
  129.         Map<String, Object> parameters = new HashMap<String, Object>();  
  130.         JasperPrint jasperPrint = JasperFillManager.fillReport(jp, parameters, new JRBeanCollectionDataSource(getBaseList(alias, list)));//phrase(list)  
  131.         logger.info("Filling time : " + (System.currentTimeMillis() - start));    
  132.           
  133.         //将解析完的参数传入报表模板中并生成报表  
  134.         if(reportType.equals("pdf")){  
  135.             JasperExportManager.exportReportToPdfStream(jasperPrint, out);  
  136.         }else if(reportType.equals("xls")){  
  137.             JRXlsExporter exporter = new JRXlsExporter();  
  138.             ByteArrayOutputStream oStream = new ByteArrayOutputStream();  
  139.             exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  
  140.             exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, oStream);  
  141.             exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);  
  142.             exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);  
  143.             exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);  
  144.             exporter.exportReport();  
  145.             byte[] bytes = oStream.toByteArray();  
  146.             out.write(bytes);  
  147.         }else{  
  148.             //生成html  
  149.             JRHtmlExporter exporter = new JRHtmlExporter();  
  150.             ByteArrayOutputStream oStream = new ByteArrayOutputStream();  
  151.             exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);  
  152.             exporter.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);  
  153.             exporter.setParameter(JRHtmlExporterParameter.CHARACTER_ENCODING, "utf-8");  
  154.             exporter.setParameter(JRHtmlExporterParameter.OUTPUT_STREAM, oStream);  
  155.             exporter.exportReport();  
  156.             byte[] bytes = oStream.toByteArray();  
  157.             out.write(bytes);  
  158.         }  
  159.           
  160.         logger.info("Printing time : " + (System.currentTimeMillis() - start));  
  161.     }  
  162.   
  163.   
  164.     public  List<String[]> phrase(List<Object[]> list) {  
  165.         List<String[]> temps = new ArrayList<String[]>();  
  166.         String[] s = null;  
  167.         for (Object[] obj : list) {  
  168.             s = new String[obj.length];  
  169.             for (int i = 0; i < obj.length; i++) {  
  170.                 s[i] = obj[i].toString();  
  171.             }  
  172.             temps.add(s);  
  173.         }  
  174.         return temps;  
  175.     }  
  176.   
  177.     /** 
  178.      * 產生columnHeaders的別名(Headers[]有可能為中文,所以有必要用別名來替換) 
  179.      *  
  180.      * @param headers 
  181.      * @return 
  182.      */  
  183.     private  String[] preaseAliasColumnHeaders(String headers[]) {  
  184.         int size = headers.length;  
  185.         String[] alias = new String[size];  
  186.         for (int i = 0; i < size; i++) {  
  187.             alias[i] = aliasColumn + i;  
  188.         }  
  189.         return alias;  
  190.     }  
  191.   
  192.     /** 
  193.      * 產生Template文件 
  194.      *  
  195.      * @param headers 
  196.      * @param alias 
  197.      * @return 
  198.      * @throws JRException 
  199.      */  
  200.     private List colunsMode = new ArrayList();  
  201.     private double scaling = 1.00;  
  202.     private List<Integer> widths = new ArrayList();  
  203.     private JRDesignBand columnHeader = null;  
  204.     private int X = 0;  
  205.     private int Y = 0;  
  206.     List<String> alias = new ArrayList();  
  207.       
  208.     @SuppressWarnings("deprecation")  
  209.     private  JasperReport getJasperReport(Map pageSet, String titleStr, List coluns, String reportType) throws JRException {  
  210.         JasperDesign design = new JasperDesign();  
  211.   
  212.         // name="statistics"  
  213.         design.setName("富友erp数据导出");  
  214.   
  215.         // columnSpacing="0"  
  216.         design.setColumnSpacing(0);  
  217.         // leftMargin="30"  
  218.         design.setLeftMargin(0);  
  219.         // rightMargin="30"  
  220.         design.setRightMargin(0);  
  221.         // topMargin="20"  
  222.         design.setTopMargin(0);  
  223.         // bottomMargin="20"  
  224.         design.setBottomMargin(0);  
  225.           
  226.         design.setIgnorePagination(true);  
  227.           
  228.         //up down left rigth pageWidth pageHeigth layout(V(竖版),H(横板))  
  229.         int up = mmToPixel(Integer.parseInt(pageSet.get("up").toString()));  
  230.         int down = mmToPixel(Integer.parseInt(pageSet.get("down").toString()));  
  231.         int left = mmToPixel(Integer.parseInt(pageSet.get("left").toString()));  
  232.         int right = mmToPixel(Integer.parseInt(pageSet.get("right").toString()));  
  233.         int pageWidth = mmToPixel(Integer.parseInt(pageSet.get("pageWidth").toString()));  
  234.         int pageHeight = mmToPixel(Integer.parseInt(pageSet.get("pageHeight").toString()));  
  235.         String layout = pageSet.get("layout").toString();  
  236.           
  237.           
  238.         int tableWidth = 0;  
  239.         for (int i = 0; i < coluns.size(); i++) {  
  240.             Map map = (Map)coluns.get(i);  
  241.             tableWidth += Integer.parseInt(map.get("width").toString());  
  242.         }  
  243.           
  244.         if(reportType.equals("pdf")){  
  245.   
  246.             // columnCount="1"  
  247.             // printOrder="Vertical"  
  248.             design.setPrintOrder(JRReport.PRINT_ORDER_VERTICAL);  
  249.             // orientation="Portrait"  
  250.             design.setOrientation(JRReport.ORIENTATION_PORTRAIT);  
  251.             // pageWidth="595"  
  252.               
  253.               
  254.             //缩放值             
  255.             if(layout.equals("V")){  
  256.                 scaling = (double)(pageWidth-left-right)/(double)tableWidth;  
  257.                 design.setPageHeight(pageHeight);  
  258.                 design.setPageWidth(pageWidth);  
  259.                 design.setColumnWidth(pageWidth-left-right);  
  260.             }else{  
  261.                 scaling = (double)(pageHeight-left-right)/(double)tableWidth;  
  262.                 design.setPageHeight(pageWidth);  
  263.                 design.setPageWidth(pageHeight);  
  264.                 design.setColumnWidth(pageHeight-left-right);  
  265.             }  
  266.               
  267.             // leftMargin="30"  
  268.             design.setLeftMargin(left);  
  269.             // rightMargin="30"  
  270.             design.setRightMargin(right);  
  271.             // topMargin="20"  
  272.             design.setTopMargin(up);  
  273.             // bottomMargin="20"  
  274.             design.setBottomMargin(down);  
  275.             // whenNoDataType="NoPages"  
  276.             design.setIgnorePagination(false);  
  277.               
  278.             design.setWhenNoDataType(JRReport.WHEN_NO_DATA_TYPE_BLANK_PAGE);  
  279.             // isTitleNewPage="false"  
  280.             design.setTitleNewPage(false);  
  281.             // isSummaryNewPage="false"  
  282.             design.setSummaryNewPage(false);  
  283.         }  
  284.   
  285.   
  286.         JRDesignBand title = new JRDesignBand();  
  287.         title.setHeight(50);  
  288.         JRDesignStaticText titleText = new JRDesignStaticText();  
  289.         titleText.setText(titleStr);  
  290.         titleText.setX(0);  
  291.         titleText.setFontSize(20);  
  292.         titleText.setHeight(40);  
  293.         titleText.setWidth( (int)Math.rint(tableWidth*scaling) );  
  294.            
  295.          titleText.setTextAlignment(JRDesignStaticText.HORIZONTAL_ALIGN_CENTER);  
  296.          titleText.setPdfFontName("STSong-Light");  
  297.          titleText.setPdfEmbedded(true);  
  298.          titleText.setPdfEncoding("UniGB-UCS2-H");  
  299.          title.addElement(titleText);  
  300.           
  301.          design.setTitle(title);  
  302.   
  303.         columnHeader = new JRDesignBand();  
  304.           
  305.   
  306.   
  307.   
  308.         this.ergodicColumns(coluns, X, 0);  
  309.         columnHeader.setHeight(columnHeaderHeight*(RowLength+1));  
  310.         X = 0;  
  311.         Y = 0;  
  312.           
  313.         JRDesignBand detail = new JRDesignBand();  
  314.         detail.setHeight(detailHeight);  
  315.           
  316.         for (int j = 0; j < alias.size(); j++) {  
  317.             // define fields  
  318.             JRDesignField field = new JRDesignField();  
  319.             field.setName( alias.get(j) );  
  320.             field.setValueClass(String.class);  
  321.             design.addField(field);  
  322.               
  323.             // add text fields for displaying fields  
  324.             JRDesignTextField textField = new JRDesignTextField();  
  325.             JRDesignExpression expression = new JRDesignExpression();  
  326.             expression.setText("$F{" + alias.get(j) + "}");  
  327.             expression.setValueClass(String.class);  
  328.             textField.setExpression(expression);  
  329.             textField.setFontSize(fontSize);  
  330.             textField.setHeight(textHeight);  
  331.             textField.setWidth(widths.get(j));  
  332.             textField.setX(X);  
  333.             textField.setPdfFontName("STSong-Light");  
  334.             textField.setPdfEmbedded(true);  
  335.             textField.setPdfEncoding("UniGB-UCS2-H");  
  336.             textField.setHorizontalAlignment(JRBasePrintText.HORIZONTAL_ALIGN_CENTER);  
  337.             textField.setVerticalAlignment(JRBasePrintText.VERTICAL_ALIGN_MIDDLE);  
  338.             textField.setLeftBorder(JRBaseLine.PEN_1_POINT);  
  339.             textField.setTopBorder(JRBaseLine.PEN_1_POINT);  
  340.             textField.setRightBorder(JRBaseLine.PEN_1_POINT);  
  341.             textField.setBottomBorder(JRBaseLine.PEN_1_POINT);  
  342.             textField.setBlankWhenNull(true);  
  343.             detail.addElement(textField);  
  344.               
  345.             X += widths.get(j);  
  346.         }  
  347.           
  348.         design.setColumnHeader(columnHeader);  
  349.         design.setDetail(detail);  
  350.           
  351.         if(reportType.equals("pdf")){  
  352.             JRDesignBand pageFooter = new JRDesignBand();  
  353.             pageFooter.setHeight(20);  
  354.             JRDesignTextField footerText = new JRDesignTextField();  
  355.             JRDesignExpression expressionF = new JRDesignExpression();  
  356.             expressionF.setText("$V{PAGE_NUMBER}");  
  357.             expressionF.setValueClass(Integer.class);  
  358.             footerText.setExpression(expressionF);  
  359.             if(layout.equals("V")){  
  360.                     footerText.setX(pageWidth-right-100);  
  361.             }else{  
  362.                 footerText.setX(pageHeight-right-100);  
  363.             }  
  364.   
  365.             footerText.setFontSize(9);  
  366.             footerText.setHeight(15);  
  367.             footerText.setWidth(100);  
  368.             footerText.setPdfFontName("STSong-Light");  
  369.             footerText.setPdfEmbedded(true);  
  370.             footerText.setPdfEncoding("UniGB-UCS2-H");  
  371.             pageFooter.addElement(footerText);  
  372.             design.setPageFooter(pageFooter);             
  373.         }  
  374.   
  375.         return JasperCompileManager.compileReport(design);  
  376.     }  
  377.       
  378.     private int RowLength = 0;  
  379.     private List ergodicColumns(List array, int X, int rowLength) {  
  380.         if(rowLength>=RowLength){  
  381.             RowLength = rowLength;   
  382.         }  
  383.         List arrayC = new ArrayList();  
  384.         int w = 0;  
  385.         /** 
  386.          * 需要得到所有表头信息。 
  387.          * 如果为多级表头时,需要得到每级的表头信息,并记录其信息。  
  388.          * **/  
  389.         for(int i = 0; i<array.size(); i++){  
  390.             //创建表头信息  
  391.             Map map = (Map)array.get(i);  
  392.             int width = (int)Math.rint((Double.parseDouble(map.get("width").toString()))*scaling);  
  393.   
  394.             // add column headers  
  395.             JRDesignStaticText staticText = new JRDesignStaticText();  
  396.             staticText.setText(map.get("title").toString());  
  397.             staticText.setFontSize(columnHeaderfontSize);  
  398.             staticText.setHeight( (Integer.parseInt(map.get("length").toString())+1)*textHeight );  
  399.               
  400.             staticText.setWidth(width);  
  401.             staticText.setX(X);  
  402.             staticText.setY(rowLength*columnHeaderHeight);  
  403.             staticText.setPdfFontName("STSong-Light");  
  404.             staticText.setPdfEmbedded(true);  
  405.             staticText.setPdfEncoding("UniGB-UCS2-H");  
  406.             staticText.setHorizontalAlignment(JRBasePrintText.HORIZONTAL_ALIGN_CENTER);  
  407.             staticText.setVerticalAlignment(JRBasePrintText.VERTICAL_ALIGN_MIDDLE);  
  408.             staticText.setLeftBorder(JRBaseLine.PEN_1_POINT);  
  409.             staticText.setTopBorder(JRBaseLine.PEN_1_POINT);  
  410.             staticText.setRightBorder(JRBaseLine.PEN_1_POINT);  
  411.             staticText.setBottomBorder(JRBaseLine.PEN_1_POINT);  
  412.             columnHeader.addElement(staticText);  
  413.             if(map.get("array")==null){  
  414.                 colunsMode.add(map);  
  415.                 alias.add(map.get("name").toString());  
  416.                 this.widths.add(width);  
  417.                 w = width;  
  418.                 arrayC.add(staticText);  
  419.             }else{  
  420.                 Object[] obj = (Object[])map.get("array");  
  421.                 List lista = new ArrayList();  
  422.                 for (int j = 0; j < obj.length; j++) {  
  423.                     lista.add(obj[j]);  
  424.                 }  
  425.                 List list = this.ergodicColumns(lista, X, rowLength+1 );  
  426.                 /* 
  427.                  * 根据X坐标重新计算 每列位置。 
  428.                  * */  
  429.                 staticText.setX(X);  
  430.                   
  431.                 int xa = X;  
  432.                 w = 0;  
  433.                 for (int j = 0; j < list.size(); j++) {  
  434.                     JRDesignStaticText staticTextA = (JRDesignStaticText)list.get(j);  
  435.                     staticTextA.setX(xa);  
  436.                     xa = xa + staticTextA.getWidth();  
  437.                     w += staticTextA.getWidth();  
  438.                 }  
  439.                 if(w!=0){  
  440.                     staticText.setWidth(w);                   
  441.                 }else{  
  442.                     w = staticText.getWidth();   
  443.                 }  
  444.   
  445.             }  
  446.             X += w;  
  447.         }  
  448.           
  449.         return arrayC;  
  450.     }  
  451.       
  452.       
  453.   
  454.     /** 
  455.      * 利用反射機制,裝拼數據 
  456.      *  
  457.      * @param headers 
  458.      * @param list 
  459.      * @return 
  460.      * @throws Exception 
  461.      */  
  462.     private List<Object> getBaseList(List<String> headers, List<Map> list) throws Exception {  
  463.         List<Object> result = new ArrayList<Object>();  
  464.         int length = headers.size();  
  465.         DynaProperty[] dynaProps = new DynaProperty[length];  
  466.         for (int i = 0; i < length; i++) {  
  467.             dynaProps[i] = new DynaProperty(headers.get(i), String.class);  
  468.         }  
  469.         BasicDynaClass dynaClass = new BasicDynaClass("first", BasicDynaBean.class, dynaProps);  
  470.         for (Map obj : list) {  
  471.             DynaBean employee = dynaClass.newInstance();  
  472.             for (int i = 0; i < length; i++) {  
  473.                 employee.set(headers.get(i), obj.get(headers.get(i)));  
  474.             }  
  475.             result.add(employee);  
  476.         }  
  477.         return result;  
  478.     }  
  479.   
  480. }  

 

此部分为此函数的核心代码,需要使用的时候需要调用 createReport 方法来执行。

 

createReport(Map pageSet, String title, List coluns, List list, String reportType)

传入参数:pageSet纸张部分设定

Java代码   收藏代码
  1. //up down left rigth pageWidth pageHeigth layout(V(竖版),H(横板))  
  2. int up = mmToPixel(Integer.parseInt(pageSet.get("up").toString()));  
  3. int down = mmToPixel(Integer.parseInt(pageSet.get("down").toString()));  
  4. int left = mmToPixel(Integer.parseInt(pageSet.get("left").toString()));  
  5. int right = mmToPixel(Integer.parseInt(pageSet.get("right").toString()));  
  6. int pageWidth = mmToPixel(Integer.parseInt(pageSet.get("pageWidth").toString()));  
  7. int pageHeight = mmToPixel(Integer.parseInt(pageSet.get("pageHeight").toString()));  
  8. String layout = pageSet.get("layout").toString();  

 

title 打印的标题,如有必要可以进行相应的扩展

coluns 打印的表头数据

colums结构如下:

Java代码   收藏代码
  1. obj["name"] = 名称obj["title"] = 标题  
  2. obj["width"] = 表格宽度  
  3. obj["length"] = 如果为多表头的时候有效,设置此表头占用高度  
  4. obj["array"] = 如果为多表头,将其子表头信息填入(为List)  
  5. obj为Map类型   

 

reportType 导出文件的格式 pdf , xls , html 三种文件格式

 

 

组合完毕后,既能导出相应的文件出来了。

 

 

下面是结合flex 来创建 上述条件

Java代码   收藏代码
  1. <p>flex代码</p>  
Java代码   收藏代码
  1. package com.wfy.sa.basic.report  
  2. {  
  3.     import com.wfy.components.advancedDataGrid.advancedDataGridClasses.AdvancedDataGridColumnGroup;  
  4.     import com.wfy.components.commandmanage.ICommand;  
  5.     import com.wfy.components.datagridext.DataGridColumnExt;  
  6.     import com.wfy.components.datagridext.DataGridExt;  
  7.       
  8.     import flash.external.ExternalInterface;  
  9.       
  10.     import mx.rpc.events.ResultEvent;  
  11.     import mx.rpc.remoting.RemoteObject;  
  12.   
  13.     public class PrintReportByDataGridCommand implements ICommand  
  14.     {  
  15.         private var dataGrid:DataGridExt  
  16.         private var title:String;  
  17.         private var remoteObject:Object;  
  18.         private var pageSet:PageSet;  
  19.         public function PrintReportByDataGridCommand(pageSet:PageSet, title:String, dataGrid:DataGridExt)//DataGridExt 对 AdvancedDataGrid进行扩展,与我们没关系  
  20.         {  
  21.             this.title = title;  
  22.             this.pageSet = pageSet;  
  23.             this.dataGrid = dataGrid;  
  24.               
  25.             this.remoteObject = new RemoteObject("UtilFunctionService");  
  26.         }  
  27.           
  28.         private var colunsMode:Array = new Array();  
  29.   
  30.         public function execute():void  
  31.         {  
  32. //          var array:Array = this.dataGrid.columns;//.getDataGridStyleAS().getColumns();  
  33.             var array:Array = this.dataGrid.groupedColumns;  
  34.             var coluns:Array = new Array();   
  35.             coluns = this.ergodicColumns(array, 0);  
  36.               
  37.             //遍历表格高度。  
  38.             coluns = this.getRowLengthColumns(coluns, 0);  
  39.               
  40.               
  41.             var list:Array = new Array();  
  42.             var length:int = this.dataGrid.getRowsLength();  
  43.             for(var j:int=0; j<length; j++){  
  44.                 var obj:Object = new Object();  
  45.                 for(var k:int=0; k<colunsMode.length; k++){  
  46.                     obj[colunsMode[k]["name"]] = this.dataGrid.getLabel(j , colunsMode[k]["name"]);  
  47.                 }  
  48.                 list.push(obj);  
  49.             }  
  50.               
  51.             remoteObject.createReportByDataGrid(pageSet, coluns, this.title, list, "pdf");    
  52.         }  
  53.           
  54.         public function OnResult(resultEvent:ResultEvent):String  
  55.         {  
  56.             var reportUrl:String = resultEvent.result.toString();  
  57.   
  58.             ExternalInterface.call("window.open""../"+reportUrl , "打印""top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=yes, location=no, status=no""_blank");  
  59.   
  60.             return "";  
  61.         }  
  62.           
  63.           
  64.         private function getRowLengthColumns(array:Array, rowlength:int):Array {  
  65.             for(var i:int=0; i<array.length; i++){  
  66.                 if(array[i]["array"]!=null){  
  67.                     var arrayI:Array = this.getRowLengthColumns(array[i]["array"], rowlength+1);  
  68. //                  arrayI[i]["length"] = RowLength-rowlength-1;  
  69.                     array[i]["array"] = arrayI;  
  70.                     array[i]["length"] = RowLength-rowlength-1;  
  71.                 }else{  
  72.                     array[i]["length"] = RowLength-rowlength;  
  73.                 }  
  74.             }  
  75.             return array;  
  76.         }  
  77.           
  78.         private var RowLength:int = 0;  
  79.         private function ergodicColumns(array:Array, rowlength:int):Array {  
  80.             if(rowlength>=RowLength){  
  81.                 RowLength = rowlength;   
  82.             }  
  83.               
  84.             var arrayC:Array = new Array();       
  85.             /** 
  86.              * 需要得到所有表头信息。 
  87.              * 如果为多级表头时,需要得到每级的表头信息,并记录其信息。  
  88.              * **/  
  89.   
  90.             for(var i:int=0; i<array.length; i++){  
  91.                 if(array[i] is AdvancedDataGridColumnGroup){  
  92.                     var ad:AdvancedDataGridColumnGroup = array[i] as AdvancedDataGridColumnGroup;  
  93.                     if(ad.visible){  
  94. //                      if(ad.headerText!=null && ad.headerText!=""){  
  95.                             var obj:Object = new Object();  
  96.                             obj["name"] = ad.dataField;  
  97.                             obj["title"] = ad.headerText;  
  98.                             obj["width"] = ad.width;  
  99.                             obj["array"] = this.ergodicColumns(ad.children, rowlength+1 );  
  100.                             arrayC.push(obj);  
  101.                     }  
  102.                 }else if(array[i] is DataGridColumnExt){  
  103.                     var da:DataGridColumnExt = array[i] as DataGridColumnExt;  
  104.                     if(da.visible){  
  105.                         if(da.dataField!=null && da.dataField!="" && da.headerText!=null && da.headerText!=""){  
  106.                             var obj:Object = new Object();  
  107.                             obj["name"] = da.dataField;  
  108.                             obj["title"] = da.headerText;  
  109.                             obj["width"] = da.width;//可能需要重新计算  
  110.                             arrayC.push(obj);  
  111.                             colunsMode.push(obj);  
  112.                         }  
  113.                     }  
  114.                 }  
  115.             }  
  116.             return arrayC;  
  117.         }  
  118.           
  119.     }  
  120. }  

 

 此函数是我们在flex中做的操作,根据flex的datagrid得到打印的信息,以及表头信息。并传送给后台生成打印文件。

 

你可能感兴趣的:(html,Excel)