动态生成报表

项目里用到了jasperreport,平时都是用ireport来设计好报表模板直接使用就好了,但是碰到动态表头等情况就比较麻烦了,而且有些报表可能仅是针对一个数据表或者说一个实体对象的操作,对于这种报表一个个设计JRXML也比较麻烦,尝试了一下编程的方式来生成报表,只是个简单的测试。在网上找一些资料发现纯编程来写报表的相关内容很少,也是看了相关的API后才写了个例子。

ReportProcess.java是一个简单的用来构造、编译并导出报表的类。

Java代码
1.package jasper.test;  
2. 
3.import java.io.FileInputStream;  
4.import java.io.InputStream;  
5.import java.io.InputStreamReader;  
6. 
7.import net.sf.jasperreports.engine.JRException;  
8.import net.sf.jasperreports.engine.JasperCompileManager;  
9.import net.sf.jasperreports.engine.JasperExportManager;  
10.import net.sf.jasperreports.engine.JasperFillManager;  
11.import net.sf.jasperreports.engine.JasperPrint;  
12.import net.sf.jasperreports.engine.JasperReport;  
13.import net.sf.jasperreports.engine.design.JRDesignBand;  
14.import net.sf.jasperreports.engine.design.JRDesignExpression;  
15.import net.sf.jasperreports.engine.design.JRDesignField;  
16.import net.sf.jasperreports.engine.design.JRDesignStaticText;  
17.import net.sf.jasperreports.engine.design.JRDesignTextField;  
18.import net.sf.jasperreports.engine.design.JasperDesign;  
19. 
20.public class ReportProcess {  
21. 
22.    public static void main(String[] args) {  
23.        try {  
24.            JasperReport jp = getJasperReport();  
25.            InputStream in = new FileInputStream(  
26.                    "src/test/java/jasper/test/Data.csv");// 换成自己目录  
27.            CsvDataSource csvDataSource = new CsvDataSource(  
28.                    new InputStreamReader(in));  
29.            in.close();  
30. 
31.            JasperPrint jpr = JasperFillManager.fillReport(jp, null,  
32.                    csvDataSource);  
33.            JasperExportManager.exportReportToHtmlFile(jpr, "c:/test.html");// 写的时候随便指定了个查看的目录  
34.        } catch (Exception e) {  
35.            e.printStackTrace();  
36.        }  
37.    }  
38. 
39.    public static JasperReport getJasperReport() throws JRException {  
40.        JasperDesign design = new JasperDesign();  
41.        design.setName("testReport");  
42. 
43.        JRDesignBand title = new JRDesignBand();  
44.        title.setHeight(50);  
45.        JRDesignStaticText titleText = new JRDesignStaticText();  
46.        titleText.setText("test report");  
47.        titleText.setX(230);  
48.        titleText.setFontSize(20);  
49.        titleText.setHeight(50);  
50.        titleText.setWidth(100);  
51.        title.addElement(titleText);  
52.        design.setTitle(title);  
53. 
54.        String[] headers = { "name", "age", "gender", "like" };  
55.        JRDesignBand columnHeader = new JRDesignBand();  
56.        columnHeader.setHeight(30);  
57. 
58.        JRDesignBand detail = new JRDesignBand();  
59.        detail.setHeight(30);  
60. 
61.        for (int i = 0; i < headers.length; i++) {  
62.            // add column headers  
63.            JRDesignStaticText staticText = new JRDesignStaticText();  
64.            staticText.setText(headers[i]);  
65.            staticText.setFontSize(16);  
66.            staticText.setHeight(30);  
67.            staticText.setWidth(50);  
68.            staticText.setX(50 * i);  
69.            columnHeader.addElement(staticText);  
70. 
71.            // define fields  
72.            JRDesignField field = new JRDesignField();  
73.            field.setName(headers[i]);  
74.            field.setValueClass(String.class);  
75.            design.addField(field);  
76. 
77.            // add text fields for displaying fields  
78.            JRDesignTextField textField = new JRDesignTextField();  
79.            JRDesignExpression expression = new JRDesignExpression();  
80.            expression.setText("$F{" + headers[i] + "}");  
81.            expression.setValueClass(String.class);  
82.            textField.setExpression(expression);  
83.            textField.setFontSize(14);  
84.            textField.setHeight(30);  
85.            textField.setWidth(50);  
86.            textField.setX(50 * i);  
87.            detail.addElement(textField);  
88.        }  
89.        design.setColumnHeader(columnHeader);  
90.        design.setDetail(detail);  
91. 
92.        return JasperCompileManager.compileReport(design);  
93.    }  
94. 
95.} 
package jasper.test;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

import net.sf.jasperreports.engine.JRException;
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.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;

public class ReportProcess {

public static void main(String[] args) {
try {
JasperReport jp = getJasperReport();
InputStream in = new FileInputStream(
"src/test/java/jasper/test/Data.csv");// 换成自己目录
CsvDataSource csvDataSource = new CsvDataSource(
new InputStreamReader(in));
in.close();

JasperPrint jpr = JasperFillManager.fillReport(jp, null,
csvDataSource);
JasperExportManager.exportReportToHtmlFile(jpr, "c:/test.html");// 写的时候随便指定了个查看的目录
} catch (Exception e) {
e.printStackTrace();
}
}

public static JasperReport getJasperReport() throws JRException {
JasperDesign design = new JasperDesign();
design.setName("testReport");

JRDesignBand title = new JRDesignBand();
title.setHeight(50);
JRDesignStaticText titleText = new JRDesignStaticText();
titleText.setText("test report");
titleText.setX(230);
titleText.setFontSize(20);
titleText.setHeight(50);
titleText.setWidth(100);
title.addElement(titleText);
design.setTitle(title);

String[] headers = { "name", "age", "gender", "like" };
JRDesignBand columnHeader = new JRDesignBand();
columnHeader.setHeight(30);

JRDesignBand detail = new JRDesignBand();
detail.setHeight(30);

for (int i = 0; i < headers.length; i++) {
// add column headers
JRDesignStaticText staticText = new JRDesignStaticText();
staticText.setText(headers[i]);
staticText.setFontSize(16);
staticText.setHeight(30);
staticText.setWidth(50);
staticText.setX(50 * i);
columnHeader.addElement(staticText);

// define fields
JRDesignField field = new JRDesignField();
field.setName(headers[i]);
field.setValueClass(String.class);
design.addField(field);

// add text fields for displaying fields
JRDesignTextField textField = new JRDesignTextField();
JRDesignExpression expression = new JRDesignExpression();
expression.setText("$F{" + headers[i] + "}");
expression.setValueClass(String.class);
textField.setExpression(expression);
textField.setFontSize(14);
textField.setHeight(30);
textField.setWidth(50);
textField.setX(50 * i);
detail.addElement(textField);
}
design.setColumnHeader(columnHeader);
design.setDetail(detail);

return JasperCompileManager.compileReport(design);
}

}


CsvDataSource.java是摘自JASER例子里的一个数据源实现,有现成的做例子的时候就拿来用了,用这个比较简单,不用写数据库那一堆。

Java代码
1.package jasper.test;  
2. 
3.import java.io.FileNotFoundException;  
4.import java.io.IOException;  
5.import java.io.Reader;  
6.import java.util.List;  
7. 
8.import net.sf.jasperreports.engine.JRException;  
9.import net.sf.jasperreports.engine.JRField;  
10.import net.sf.jasperreports.engine.JRRewindableDataSource;  
11.import au.com.bytecode.opencsv.CSVReader;  
12. 
13./** 
14. *  
15. * 这个类摘自JASPER带的一个例子里的CSV数据源实现。 
16. *  
17. */ 
18.public class CsvDataSource implements JRRewindableDataSource {  
19.    private CSVReader csvReader;  
20.    private List rows;  
21.    private int currentRowIndex = -1;  
22.    private int currentColIndex = 0;  
23.    private int totalRows;  
24. 
25.    public CsvDataSource(Reader reader) {  
26.        try {  
27.            csvReader = new CSVReader(reader);  
28.            rows = csvReader.readAll();  
29.            totalRows = rows.size();  
30.        } catch (FileNotFoundException e) {  
31.            e.printStackTrace();  
32.        } catch (IOException e) {  
33.            e.printStackTrace();  
34.        }  
35.    }  
36. 
37.    public boolean next() throws JRException {  
38.        boolean retVal = true;  
39. 
40.        currentRowIndex++;  
41.        currentColIndex = 0;  
42. 
43.        if (currentRowIndex >= totalRows) {  
44.            retVal = false;  
45.        }  
46. 
47.        return retVal;  
48.    }  
49. 
50.    public Object getFieldValue(JRField arg0) throws JRException {  
51.        String value = null;  
52.        String[] currentRow = (String[]) rows.get(currentRowIndex);  
53. 
54.        value = currentRow[currentColIndex];  
55.        currentColIndex++;  
56. 
57.        return value;  
58.    }  
59. 
60.    public void moveFirst() throws JRException {  
61.        currentRowIndex = 0;  
62.        currentColIndex = 0;  
63.    }  
64.} 
package jasper.test;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.util.List;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
import net.sf.jasperreports.engine.JRRewindableDataSource;
import au.com.bytecode.opencsv.CSVReader;

/**
*
* 这个类摘自JASPER带的一个例子里的CSV数据源实现。
*
*/
public class CsvDataSource implements JRRewindableDataSource {
private CSVReader csvReader;
private List rows;
private int currentRowIndex = -1;
private int currentColIndex = 0;
private int totalRows;

public CsvDataSource(Reader reader) {
try {
csvReader = new CSVReader(reader);
rows = csvReader.readAll();
totalRows = rows.size();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public boolean next() throws JRException {
boolean retVal = true;

currentRowIndex++;
currentColIndex = 0;

if (currentRowIndex >= totalRows) {
retVal = false;
}

return retVal;
}

public Object getFieldValue(JRField arg0) throws JRException {
String value = null;
String[] currentRow = (String[]) rows.get(currentRowIndex);

value = currentRow[currentColIndex];
currentColIndex++;

return value;
}

public void moveFirst() throws JRException {
currentRowIndex = 0;
currentColIndex = 0;
}
}


Data.csv里的数据。

Java代码
1.jim,12,male,basketball  
2.lily,13,female,dancing  
3.david,23,male,swimming  
4.su,23,female,running 
jim,12,male,basketball
lily,13,female,dancing
david,23,male,swimming
su,23,female,running


结果大致是这个样子。

Java代码
1.                 test report    
2.name    age   gender   like    
3.jim     12    male     basketb    
4.lily    13    female   dancing    
5.david   23    male     swimmi  
6.su      23    female   running  
                  test report 
name    age   gender   like 
jim     12    male     basketb 
lily    13    female   dancing 
david   23    male     swimmi
su      23    female   running


这里就是个实验性的代码,但至少可以知道,我们可以通过一些手段来编程处理JASPER的报表。可以写得更完善一些,动态获取表头个数与内容,写QUERY查询,填充报表。
比如一张表有一部分表头是不定的,那就可以在程序中追加表头定义,追加字段定义等。

你可能感兴趣的:(编程,.net,F#)