maven dependencies (pom.xml)
<dependencies>
<!-- Jasper Report **************************************************-->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>5.0.1</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports-fonts</artifactId>
<version>5.0.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
<!-- Jasper Report **************************************************-->
...
...
...
</dependencies>
JasperExporter.java
package com.blogspot.na5cent.jasperlearning;
import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Map;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.fill.JRFileVirtualizer;
import net.sf.jasperreports.engine.util.JRLoader;
/**
*
* @author redcrow create 18/12/2013 link
* http://na5cent.blogspot.com/2013/12/jasperexporter-java.html
*/
public class JasperExporter {
private static int jasperReportFileVirtualizerMaxSize = 2;
private static String reportTemporaryPath = System.getProperty("java.io.tmpdir");
public static void setJasperReportFileVirtualizerMaxSize(int virtualizerMaxSize) {
jasperReportFileVirtualizerMaxSize = virtualizerMaxSize;
}
public static void setReportTemporaryPath(String path) {
reportTemporaryPath = path;
}
public static int getJasperReportFileVirtualizerMaxSize() {
return jasperReportFileVirtualizerMaxSize;
}
public static String getReportTemporaryPath() {
return reportTemporaryPath;
}
private static abstract class ExecuteCaller {
private Connection databaseConnection = null;
public ExecuteCaller() {
}
public ExecuteCaller(Connection databaseConnection) {
this.databaseConnection = databaseConnection;
}
/**
* @param virtualizer
* @throws Exception
*/
public abstract void execute(JRFileVirtualizer virtualizer) throws Exception;
public void call() throws Exception {
JRFileVirtualizer virtualizer = null;
try {
//write report to temp file, protect out of memory (for big report)
virtualizer = new JRFileVirtualizer(jasperReportFileVirtualizerMaxSize, reportTemporaryPath);
execute(virtualizer);
} finally {
if (virtualizer != null) {
virtualizer.cleanup(); //clean up temp file
}
if (databaseConnection != null) {
databaseConnection.close(); //close database connection
}
}
}
}
private static boolean fileIs(File file, String extension) {
return file.getName().toLowerCase().endsWith(extension);
}
private static void exportToPdf(JasperPrint jasperPrint, File pdfFile) throws Exception {
if (!fileIs(pdfFile, ".pdf")) {
throw new IllegalArgumentException("require .pdf only");
}
JRPdfExporter exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.OUTPUT_FILE, pdfFile);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.exportReport();
}
private static void exportToExcel(JasperPrint jasperPrint, File excelFile) throws Exception {
if (!fileIs(excelFile, ".xls")) {
throw new IllegalArgumentException("require .xls only");
}
JExcelApiExporter exporter = new JExcelApiExporter();
exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS, Boolean.TRUE);
exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
exporter.setParameter(JRXlsExporterParameter.IS_IGNORE_GRAPHICS, Boolean.FALSE);
//
exporter.setParameter(JRXlsExporterParameter.OUTPUT_FILE, excelFile);
exporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
exporter.exportReport();
}
private static void exportToWord(JasperPrint jasperPrint, File wordFile) throws Exception {
if (!fileIs(wordFile, ".doc")) {
throw new IllegalArgumentException("require .doc only");
}
JRRtfExporter exporter = new JRRtfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE, wordFile);
exporter.exportReport();
}
/**
* for export jasper report with database connection to output pdf file
* (.pdf)
*
* @param jasper
* @param databaseConnection
* @param reportParam
* @param pdfFile
* @throws Exception
*/
public static void exportWithConnectionToPdfFile(final JasperReport jasper, final Connection databaseConnection, final Map reportParam, final File pdfFile) throws Exception {
new ExecuteCaller(databaseConnection) {
@Override
public void execute(JRFileVirtualizer virtualizer) throws Exception {
reportParam.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasper, reportParam, databaseConnection);
exportToPdf(jasperPrint, pdfFile);
}
}.call();
}
/**
* for export jasper report (.jasper input stream) with database connection
* to output pdf file (.pdf)
*
* @param jasperInputStream
* @param databaseConnection
* @param reportParam
* @param pdfFile
* @throws Exception
*/
public static void exportWithConnectionToPdfFile(final InputStream jasperInputStream, final Connection databaseConnection, final Map reportParam, final File pdfFile) throws Exception {
try {
JasperReport jasper = (JasperReport) JRLoader.loadObject(jasperInputStream);
exportWithConnectionToPdfFile(jasper, databaseConnection, reportParam, pdfFile);
} finally {
if (jasperInputStream != null) {
jasperInputStream.close();
}
}
}
/**
* for export jasper report with database connection to output excel file
* (.xls)
*
* @param jasper
* @param databaseConnection
* @param reportParam
* @param excelFile
* @throws Exception
*/
public static void exportWithConnectionToExcelFile(final JasperReport jasper, final Connection databaseConnection, final Map reportParam, final File excelFile) throws Exception {
new ExecuteCaller(databaseConnection) {
@Override
public void execute(JRFileVirtualizer virtualizer) throws Exception {
reportParam.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasper, reportParam, databaseConnection);
exportToExcel(jasperPrint, excelFile);
}
}.call();
}
/**
* for export jasper report (.jasper input stream) with database connection
* to output excel file (.xls)
*
* @param jasperInputStream
* @param databaseConnection
* @param reportParam
* @param excelFile
* @throws Exception
*/
public static void exportWithConnectionToExcelFile(final InputStream jasperInputStream, final Connection databaseConnection, final Map reportParam, final File excelFile) throws Exception {
try {
JasperReport jasper = (JasperReport) JRLoader.loadObject(jasperInputStream);
exportWithConnectionToExcelFile(jasper, databaseConnection, reportParam, excelFile);
} finally {
if (jasperInputStream != null) {
jasperInputStream.close();
}
}
}
/**
* for export jasper report with database connection to output word file
* (.doc)
*
* @param jasper
* @param databaseConnection
* @param reportParam
* @param wordFile
* @throws Exception
*/
public static void exportWithConnectionToWordFile(final JasperReport jasper, final Connection databaseConnection, final Map reportParam, final File wordFile) throws Exception {
new ExecuteCaller(databaseConnection) {
@Override
public void execute(JRFileVirtualizer virtualizer) throws Exception {
reportParam.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasper, reportParam, databaseConnection);
exportToWord(jasperPrint, wordFile);
}
}.call();
}
/**
* for export jasper report (.jasper input stream) with database connection
* to output word file (.doc)
*
* @param jasperInputStream
* @param databaseConnection
* @param reportParam
* @param wordFile
* @throws Exception
*/
public static void exportWithConnectionToWordFile(final InputStream jasperInputStream, final Connection databaseConnection, final Map reportParam, final File wordFile) throws Exception {
try {
JasperReport jasper = (JasperReport) JRLoader.loadObject(jasperInputStream);
exportWithConnectionToWordFile(jasper, databaseConnection, reportParam, wordFile);
} finally {
if (jasperInputStream != null) {
jasperInputStream.close();
}
}
}
/**
* for export jasper report with beans to output pdf file (.pdf)
*
* @param jasper
* @param models
* @param reportParam
* @param pdfFile
* @throws Exception
*/
public static void exportWithBeansToPdfFile(final JasperReport jasper, final Object[] models, final Map reportParam, final File pdfFile) throws Exception {
new ExecuteCaller() {
@Override
public void execute(JRFileVirtualizer virtualizer) throws Exception {
reportParam.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
//pass models into jasper bean
JRBeanArrayDataSource beans = new JRBeanArrayDataSource(models);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasper, reportParam, beans);
exportToPdf(jasperPrint, pdfFile);
}
}.call();
}
/**
* for export jasper report (jasper input sream) with beans to output pdf
* file (.pdf)
*
* @param jasperInputStream
* @param models
* @param reportParam
* @param pdfFile
* @throws Exception
*/
public static void exportWithBeansToPdfFile(final InputStream jasperInputStream, final Object[] models, final Map reportParam, final File pdfFile) throws Exception {
try {
JasperReport jasper = (JasperReport) JRLoader.loadObject(jasperInputStream);
exportWithBeansToPdfFile(jasper, models, reportParam, pdfFile);
} finally {
if (jasperInputStream != null) {
jasperInputStream.close();
}
}
}
/**
* for export jasper report with beans to output excel file (.xls)
*
* @param jasper
* @param models
* @param reportParam
* @param excelFile
* @throws Exception
*/
public static void exportWithBeansToExcelFile(final JasperReport jasper, final Object[] models, final Map reportParam, final File excelFile) throws Exception {
new ExecuteCaller() {
@Override
public void execute(JRFileVirtualizer virtualizer) throws Exception {
reportParam.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
JRBeanArrayDataSource beans = new JRBeanArrayDataSource(models);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasper, reportParam, beans);
exportToExcel(jasperPrint, excelFile);
}
}.call();
}
/**
* for export jasper report(.jasper input stream) with beans to output excel
* file (.xls)
*
* @param jasperInputStream
* @param models
* @param reportParam
* @param excelFile
* @throws Exception
*/
public static void exportWithBeansToExcelFile(final InputStream jasperInputStream, final Object[] models, final Map reportParam, final File excelFile) throws Exception {
try {
JasperReport jasper = (JasperReport) JRLoader.loadObject(jasperInputStream);
exportWithBeansToExcelFile(jasper, models, reportParam, excelFile);
} finally {
if (jasperInputStream != null) {
jasperInputStream.close();
}
}
}
/**
* for export jasper report with beans to output word file (.doc)
*
* @param jasper
* @param models
* @param reportParam
* @param wordFile
* @throws Exception
*/
public static void exportWithBeansToWordFile(final JasperReport jasper, final Object[] models, final Map reportParam, final File wordFile) throws Exception {
new ExecuteCaller() {
@Override
public void execute(JRFileVirtualizer virtualizer) throws Exception {
reportParam.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
JRBeanArrayDataSource beans = new JRBeanArrayDataSource(models);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasper, reportParam, beans);
exportToWord(jasperPrint, wordFile);
}
}.call();
}
/**
* for export jasper report(.jasper input stream) with beans to output word
* file (.doc)
*
* @param jasperInputStream
* @param models
* @param reportParam
* @param wordFile
* @throws Exception
*/
public static void exportWithBeansToWordFile(final InputStream jasperInputStream, final Object[] models, final Map reportParam, final File wordFile) throws Exception {
try {
JasperReport jasper = (JasperReport) JRLoader.loadObject(jasperInputStream);
exportWithBeansToWordFile(jasper, models, reportParam, wordFile);
} finally {
if (jasperInputStream != null) {
jasperInputStream.close();
}
}
}
/**
* for export jasper report with database connection to output jasper print
* file (.jasperPrint)
*
* @param jasper
* @param databaseConnection
* @param reportParam
* @param outputJasperPrintFile
* @throws Exception
*/
public static void exportJasperPrintWithConnectionToFile(final JasperReport jasper, final Connection databaseConnection, final Map reportParam, final File outputJasperPrintFile) throws Exception {
new ExecuteCaller(databaseConnection) {
@Override
public void execute(JRFileVirtualizer virtualizer) throws Exception {
reportParam.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
JasperFillManager.fillReportToFile(jasper, outputJasperPrintFile.getPath(), reportParam, databaseConnection);
}
}.call();
}
/**
* for export jasper report with database connection to output jasper print
* file (.jasperPrint)
*
* @param jasperInputStream
* @param databaseConnection
* @param reportParam
* @param outputJasperPrintFile
* @throws Exception
*/
public static void exportJasperPrintWithConnectionToFile(final InputStream jasperInputStream, final Connection databaseConnection, final Map reportParam, final File outputJasperPrintFile) throws Exception {
new ExecuteCaller(databaseConnection) {
@Override
public void execute(JRFileVirtualizer virtualizer) throws Exception {
try {
reportParam.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
JasperReport jasper = (JasperReport) JRLoader.loadObject(jasperInputStream);
JasperFillManager.fillReportToFile(jasper, outputJasperPrintFile.getPath(), reportParam, databaseConnection);
} finally {
if (jasperInputStream != null) {
jasperInputStream.close();
}
}
}
}.call();
}
/**
* for export jasper report with beans to output jasper print file
* (.jasperPrint)
*
* @param jasper
* @param models
* @param reportParam
* @param outputJasperPrintFile
* @throws Exception
*/
public static void exportJasperPrintWithBeansToFile(final JasperReport jasper, final Object[] models, final Map reportParam, final File outputJasperPrintFile) throws Exception {
new ExecuteCaller() {
@Override
public void execute(JRFileVirtualizer virtualizer) throws Exception {
JRBeanArrayDataSource beans = new JRBeanArrayDataSource(models);
JasperFillManager.fillReportToFile(jasper, outputJasperPrintFile.getPath(), reportParam, beans);
}
}.call();
}
/**
* for export jasper print file to pdf file (.pdf)
*
* @param jasperPrintFile
* @param pdfFile
* @throws Exception
*/
public static void exportFromJasperPrintFileToPdfFile(final File jasperPrintFile, final File pdfFile) throws Exception {
new ExecuteCaller() {
@Override
public void execute(JRFileVirtualizer virtualizer) throws Exception {
JasperPrint jasperPrint = JRLoader.loadJasperPrintFromFile(jasperPrintFile.getPath(), virtualizer);
exportToPdf(jasperPrint, pdfFile);
}
}.call();
}
/**
* for export jasper print file to excel file (.xls)
*
* @param jasperPrintFile
* @param excelFile
* @throws Exception
*/
public static void exportFromJasperPrintFileToExcelFile(final File jasperPrintFile, final File excelFile) throws Exception {
new ExecuteCaller() {
@Override
public void execute(JRFileVirtualizer virtualizer) throws Exception {
JasperPrint jasperPrint = JRLoader.loadJasperPrintFromFile(jasperPrintFile.getPath(), virtualizer);
exportToExcel(jasperPrint, excelFile);
}
}.call();
}
/**
* for export jasper print file to word file (.doc)
*
* @param jasperPrintFile
* @param wordFile
* @throws Exception
*/
public static void exportFromJasperPrintFileToWordFile(final File jasperPrintFile, final File wordFile) throws Exception {
new ExecuteCaller() {
@Override
public void execute(JRFileVirtualizer virtualizer) throws Exception {
JasperPrint jasperPrint = JRLoader.loadJasperPrintFromFile(jasperPrintFile.getPath(), virtualizer);
exportToWord(jasperPrint, wordFile);
}
}.call();
}
}
ใช้คู่กับตัว export สำเร็จรูป
package com.blogspot.na5cent.jasperlearning;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
/**
* @author redcrow
* create 11/11/2014
* link http://na5cent.blogspot.com/2013/12/jasperexporter-java.html
*/
public class ReportExporter {
private static final Logger LOG = LoggerFactory.getLogger(ReportExporter.class);
/**/
private static final String JASPER_FILE_EXTENSION = ".jasper";
private static final String JASPERPRINT_FILE_EXTENSION = ".jasperPrint";
private static final String MSWORD_FILE_EXTENSION = ".doc";
private static final String PDF_FILE_EXTENSION = ".pdf";
private static final String EXCEL_FILE_EXTENSION = ".xls";
/**/
private final File jasperFile;
private String exportFileName;
private File exportFile;
private File jasperPrintFile;
private Map<String, Object> params;
private File tempDirectory;
private DataSource dataSource;
private String lastestType;
private ReportExporter(File jasperFile) {
this.jasperFile = jasperFile;
exportFileName = FilenameUtils.getBaseName(
jasperFile.getName()
);
}
private static boolean isJasperFile(File file) {
return file.getName()
.toLowerCase()
.endsWith(JASPER_FILE_EXTENSION);
}
public static ReportExporter fromJasper(File jasperFile) {
if (!isJasperFile(jasperFile) || !jasperFile.exists()) {
throw new IllegalArgumentException(
"not " + JASPER_FILE_EXTENSION + " file"
);
}
return new ReportExporter(jasperFile);
}
/**
* root is class path
*
* @param jasperFilePath
* @return
*/
public static ReportExporter fromJasper(String jasperFilePath) {
return fromJasper(new File(ReportExporter.class.getResource(
jasperFilePath
).getPath()));
}
private Map<String, Object> getParams() {
if (params == null) {
params = new HashMap<>();
}
return params;
}
private File getTempDirectory() {
if (tempDirectory == null) {
String path = System.getProperty("java.io.tmpdir");
tempDirectory = new File(path);
}
return tempDirectory;
}
public ReportExporter withTempDirectory(File tempDirectory) {
this.tempDirectory = tempDirectory;
return this;
}
public ReportExporter addParam(String key, Object value) {
getParams().put(key, value);
return this;
}
public ReportExporter setExportFileName(String fileName) {
this.exportFileName = fileName;
return this;
}
private File createJasperPrintFile() {
return new File(
getTempDirectory(),
exportFileName + JASPERPRINT_FILE_EXTENSION
);
}
public File getExportFile() {
return exportFile;
}
public File getJasperPrintFile() {
return jasperPrintFile;
}
public File getJasperFile() {
return jasperFile;
}
public ReportExporter withDataSource(DataSource dataSource) {
this.dataSource = dataSource;
return this;
}
private void filterReport2JasperPrint() {
if (dataSource == null) {
throw new NullPointerException("require dataSource.");
}
try {
jasperPrintFile = createJasperPrintFile();
JasperExporter.exportJasperPrintWithConnectionToFile(
new FileInputStream(jasperFile),
dataSource.getConnection(),
getParams(),
jasperPrintFile
);
} catch (Exception ex) {
LOG.warn(null, ex);
jasperPrintFile = null;
}
}
private File newExportFile(String extension) {
return new File(
getTempDirectory(),
exportFileName + extension
);
}
private void print2WordFile() throws Exception {
exportFile = newExportFile(MSWORD_FILE_EXTENSION);
JasperExporter.exportFromJasperPrintFileToWordFile(
jasperPrintFile,
exportFile
);
}
private void print2PdfFile() throws Exception {
exportFile = newExportFile(PDF_FILE_EXTENSION);
JasperExporter.exportFromJasperPrintFileToPdfFile(
jasperPrintFile,
exportFile
);
}
private void print2ExcelFile() throws Exception {
exportFile = newExportFile(EXCEL_FILE_EXTENSION);
JasperExporter.exportFromJasperPrintFileToExcelFile(
jasperPrintFile,
exportFile
);
}
/**
* for clear export file caching
*/
public void reset() {
jasperPrintFile = null;
exportFile = null;
}
private boolean match(String type) {
if (!StringUtils.hasText(type)) {
return false;
}
type = type.toLowerCase();
return type.equals("word")
|| type.equals("excel")
|| type.equals("pdf");
}
/**
* if export success will return true else false
*
* @return
*/
public boolean isExported() {
return exportFile != null;
}
private void exportFromType(String type) {
try {
type = type.toLowerCase();
switch (type) {
case "word":
print2WordFile();
break;
case "excel":
print2ExcelFile();
break;
default:
print2PdfFile();
break;
}
} catch (Exception ex) {
LOG.warn(null, ex);
exportFile = null;
}
}
/**
* @param type word, excel or pdf only
* @return export file
*/
public File export(String type) {
if (!match(type)) {
throw new IllegalArgumentException(
"type must word, excel or pdf only."
);
}
if (jasperPrintFile == null) {
filterReport2JasperPrint();
}
boolean useCache = type.equals(lastestType) && exportFile != null;
if (jasperPrintFile != null && !useCache) {
exportFromType(type);
lastestType = type;
}
return exportFile;
}
}
example
...
String JASPER_FILE = ...
DataSource dataSource = ...
...
...
ReportExporter exporter = ReportExporter.fromJasper(JASPER_FILE)
.withDataSource(dataSource)
.withTempDirectory(JasperReports.getTempDirectory());
...
...
exporter.addParam("hcodes", ...);
...
exporter.export("pdf");

ไม่มีความคิดเห็น:
แสดงความคิดเห็น