天天看點

ireport java 變量_ireport5.6.0+jasperreports 使用java對象做為資料源導出excel或者Pdf

ireport5.6.0安裝不多說

安裝完成後啟動可能閃退,主要是ireport5.6.0需要jdk1.7才能運作,1.8就會閃退。

修改ireport jdk

修改 C:\Program Files (x86)\Jaspersoft\iReport-5.6.0\etc\ireport.conf (預設路徑) 下

#jdkhome="/path/to/jdk"

jdkhome="C:\programs\Java\jdk1.7.0_71"

模版

ireport java 變量_ireport5.6.0+jasperreports 使用java對象做為資料源導出excel或者Pdf
ireport java 變量_ireport5.6.0+jasperreports 使用java對象做為資料源導出excel或者Pdf

① 對應代碼中paramMap中的變量

② 對應代碼中datas中的資料的名稱

③ 計算數,需要注意計算類型

ireport java 變量_ireport5.6.0+jasperreports 使用java對象做為資料源導出excel或者Pdf
ireport java 變量_ireport5.6.0+jasperreports 使用java對象做為資料源導出excel或者Pdf

注意事項

資料中有中文需要設定字型,否則可能列印不出來。

ireport java 變量_ireport5.6.0+jasperreports 使用java對象做為資料源導出excel或者Pdf

.jasper是.jrxml編譯過後的檔案

ireport java 變量_ireport5.6.0+jasperreports 使用java對象做為資料源導出excel或者Pdf

資料源設定

ireport java 變量_ireport5.6.0+jasperreports 使用java對象做為資料源導出excel或者Pdf
ireport java 變量_ireport5.6.0+jasperreports 使用java對象做為資料源導出excel或者Pdf

java代碼

public static void main(String[] args) {

String exportType = "xlsx";

String defaultTemplatePath = "D:\\report1.jasper";

Map paramMap = new HashMap<>();

paramMap.put("usid", "[email protected]");

paramMap.put("usna", "張三");

paramMap.put("curDate", DateUtil.date2String(new Date()));

List> datas = new ArrayList<>();

for (int i = 0; i < 3; i++) {

Map temp = new HashMap<>();

temp.put("key1", "key----" + i);

temp.put("val1", "val====" + i);

temp.put("cnt", 1);

datas.add(temp);

}

JRDataSource dataSource = new JRMapCollectionDataSource(datas);

try {

JasperPrint jasperPrint = JasperFillManager.fillReport(defaultTemplatePath, paramMap, dataSource);

String targetFileName = "D:\\test_" + DateUtil.date2String(new Date(), DateUtil.yyyyMMddHHmmss) + "." + exportType;

if ("pdf".equalsIgnoreCase(exportType)) {

JasperExportManager.exportReportToPdfFile(jasperPrint, targetFileName);

} else if ("xlsx".equalsIgnoreCase(exportType)) {

JRXlsxExporter exporter = new JRXlsxExporter();

SimpleXlsxReportConfiguration configuration = new SimpleXlsxReportConfiguration();

configuration.setWhitePageBackground(true);

configuration.setRemoveEmptySpaceBetweenRows(true);// 空行

configuration.setRemoveEmptySpaceBetweenColumns(true);// 空列

exporter.setConfiguration(configuration);

// 設定輸入項

ExporterInput exporterInput = new SimpleExporterInput(jasperPrint);

exporter.setExporterInput(exporterInput);

// 設定輸出項

OutputStreamExporterOutput exporterOutput = new SimpleOutputStreamExporterOutput(targetFileName);

exporter.setExporterOutput(exporterOutput);

exporter.exportReport();

}

System.out.println("導出成功:" + targetFileName);

} catch (Exception e) {

e.printStackTrace();

}

}

效果預覽

ireport java 變量_ireport5.6.0+jasperreports 使用java對象做為資料源導出excel或者Pdf