使用Spring Boot和JasperReports生成报表
import net.sf.jasperreports.engine.*;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
@Service
public class ReportService {
@Resource
private ResourceLoader resourceLoader;
public JasperPrint generateReport(String reportSource, Map<String, Object> parameters) throws Exception {
Resource resource = resourceLoader.getResource("classpath:" + reportSource);
FileInputStream fis = new FileInputStream(resource.getFile());
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(fis);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JREmptyDataSource());
fis.close();
return jasperPrint;
}
public byte[] exportReport(JasperPrint jasperPrint, String exportFormat) throws Exception {
Exporter exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, new ByteArrayOutputStream());
exporter.exportReport();
return ((ByteArrayOutputStream) exporter.getParameter(JRExporterParameter.OUTPUT_STREAM)).toByteArray();
}
}
这个示例代码提供了一个简单的服务类,用于生成和导出报表。generateReport
方法接受报表源路径和参数,使用JasperReports库来填充和编译报表,然后返回JasperPrint
对象。exportReport
方法接受JasperPrint
对象和导出格式,并将报表导出为字节数组。这个服务类可以被Spring框架注入到其他需要生成报表的组件中。
评论已关闭