`

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

 
阅读更多

使用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. }  
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纸张部分设定

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();   
		//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结构如下:

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

 

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

 

 

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

 

 

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

Java代码 复制代码 收藏代码
  1. <P>flex代码</P>  

flex代码

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. }  
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得到打印的信息,以及表头信息。并传送给后台生成打印文件。

分享到:
评论
1 楼 JsonTeye 2012-04-19  
您好! 我看你的代码,我现在也在做动态报表,实现功能由用户自己选择字段,然后生成SQL语句,在生成报表,你能不能发我些详细资料,谢谢!

相关推荐

    jasperreport 生成pdf实现下载与打印

    标题中的“jasperreport生成pdf实现下载与打印”是指使用JasperReports库来创建PDF报告,并提供下载和打印功能。JasperReports是一个开源的Java报表工具,它允许开发者设计、生成和导出各种类型的报表,包括PDF、...

    JasperReport动态生成报表

    JasperReport支持多种格式的报表导出,包括PDF、HTML、Excel、CSV、XML等,方便用户在不同的场景下使用和分享报表。 **6. 源码集成** JasperReport作为开源项目,其源码可被开发者直接引用或二次开发。这样不仅能够...

    jasperreport 生成pdf,html,xml,csv,xls报表,myeclipse源码

    **jasperreport** 是一个强大的开源报告生成工具,它允许开发者设计复杂的报表并以多种格式输出,如PDF、HTML、XML、CSV以及XLS。在Java应用中,jasperreport通常用于生成数据可视化的静态或交互式报表。这个源码...

    JasperReport浏览器输出PDF为空白页的解决方案

    标题中的“JasperReport浏览器输出PDF为空白页”通常意味着在使用JasperReport生成PDF报表时,浏览器未能正确显示内容。这可能是由多种原因引起的,包括但不限于以下几点: 1. **XML解析错误**:`test.jrxml`文件是...

    使用JasperReport制作PDF所需要的包(2)

    在IT行业中,报表生成是许多应用的核心功能,而JasperReport是Java环境下广泛使用的开源报表工具,它允许开发者创建复杂的报告并以多种格式输出,如PDF、HTML、Excel等。本篇文章将详细讲解如何利用JasperReport制作...

    Struts2 + JasperReport应用一:导PDF,Excel,HTML显示

    在配置Struts2的Action时,需要指定返回结果类型,比如可以定义一个名为"pdf"的结果类型,指向生成PDF的逻辑。当用户请求这个Action时,Struts2会调用相应的Action方法,执行上述步骤,最后将生成的PDF文件响应给...

    使用JasperReport输出image图像

    JasperReport是一个强大的报表生成库,通常用于创建复杂的报告布局,如表格、图表和文本等,并可以导出为多种格式,如PDF、HTML、Excel等。在寻找如何将报表直接转换为图像的过程中,开发者考虑了JasperReport自带的...

    使用jasperreports制作报表(导出pdf excel html)

    **使用JasperReports制作报表(导出PDF, Excel, HTML)** JasperReports是一款开源的Java报表库,它允许开发者创建、设计和显示复杂的报告。这个教程将介绍如何使用JasperReports来制作报表,并将其导出为PDF、...

    jasperReport+ireport制作pdf报表教程

    9. **使用jasperReport生成报表**:在Java项目中,加载JRXML文件,设置数据源,调用jasperReport API生成PDF或其他格式的报表。 10. **集成到应用**:将报表生成功能集成到你的Java应用中,如Web应用的后台服务。 ...

    jasperReport 动态合并单元格示例

    然后,使用JasperFillManager填充数据并用JasperExportManager导出报表,如PDF、Excel等格式,以查看动态合并的效果。 总的来说,jasperReport的动态合并单元格功能提供了一种灵活的方式来调整报告的布局,使得报告...

    基于Jasperreport动态单元格合并模板

    JasperReport是一款强大的开源报表工具,它允许开发者创建复杂的报表,并可以导出多种格式,如PDF、HTML、Excel等。本主题将深入探讨如何利用JasperReport实现动态单元格合并,支持多层分组排序和多分组动态合并...

    jasperreport生成多种格式的报表

    以下是使用Jasperreport生成多种格式的报表的详细知识点: 一、生成HTML格式的报表 要生成HTML格式的报表,需要使用JRHtmlExporter类,通过设置response的Content-Type和Content-Disposition头来控制报表的下载和...

    JasperReport中pdf显示中文最新jar

    在默认情况下,JasperReport使用的是iText库来生成PDF文档,但早期版本的iText对中文字符的支持并不完善,这就会导致在PDF中显示中文时出现乱码或无法显示的情况。 为了解决这个问题,我们需要引入两个特定的jar包...

    jasperreport导出Html xls PDF doc 格式文档源代码

    2. `HtmlExport.java`:此类负责将JasperReport生成的报表转换为HTML格式。它可能会调用JasperExportManager的`exportReportToHtmlFile`方法,并处理相关的CSS样式和交互元素。 3. `XlsExport.java`:这个类会处理...

    struts2+Ireport+Jasperreport实现报表导出

    JasperReport是一个开源的报表生成库,它可以读取由iReport设计的模板,结合业务数据生成各种格式的报表,如PDF、HTML、Excel等。JasperReport的强大在于它的灵活性,可以处理动态数据,支持数据分组、排序、过滤等...

    JasperReport与Java程序,导出不同格式的报表,包括pdf,excel,html,报表打印等功能

    在本教程中,我们将探讨如何利用JasperReport与iReport前端设计器来实现报表的多种格式导出,包括PDF、Excel、HTML,以及报表的打印预览功能。 首先,JasperReport的核心是报表模板,这些模板使用JRXML语言编写,...

    使用JasperReport+iReport进行WEB开发

    JasperReport是一款开源的Java报表库,它支持多种数据源,如数据库、CSV文件等,可以生成PDF、HTML、Excel等多种格式的报表。它的强大之处在于其模板驱动的设计方式,允许开发者通过XML定义报表结构和样式,然后在...

    jasperReport所需的jar文件

    2. **iText库**:jasperreports-fonts-6.x.x.jar和itext-2.x.x.jar是用于生成PDF文档所必需的。iText是一个Java库,用于生成和修改PDF文档,而jasperreports-fonts则包含了支持报表中不同字体的资源。 3. **XML解析...

Global site tag (gtag.js) - Google Analytics