springboot整合JasperReport实现报表功能
时间: 2023-07-10 15:18:55 浏览: 108
Spring Boot与JasperReports的整合步骤如下:
1.添加依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.11.0</version>
</dependency>
```
2.在application.properties中配置JasperReports相关属性
```properties
#JasperReports相关配置
spring.jasperreports.view.prefix=/jasper/
spring.jasperreports.view.suffix=.jrxml
spring.jasperreports.compiler.fail.on.warning=false
spring.jasperreports.compiler.keep.java.file=true
spring.jasperreports.compiler.xml.validation=false
spring.jasperreports.compiler.strict.validation=false
```
3.创建报表文件
在src/main/resources/jasper目录下创建报表文件,比如report.jrxml。
4.创建数据源
在代码中创建数据源,比如使用JdbcTemplate访问数据库获取数据。
```java
@Autowired
private JdbcTemplate jdbcTemplate;
public List<Map<String, Object>> getData() {
String sql = "SELECT * FROM users";
List<Map<String, Object>> data = jdbcTemplate.queryForList(sql);
return data;
}
```
5.生成报表
通过JasperReport API生成报表,并将报表输出到指定的格式,比如PDF或HTML。
```java
@Autowired
private JasperReportsViewResolver jasperReportsViewResolver;
@Autowired
private JasperReportService jasperReportService;
@RequestMapping("/report.pdf")
public ModelAndView generatePdfReport(ModelAndView modelAndView) {
Map<String, Object> parameters = new HashMap<>();
List<Map<String, Object>> data = getData();
JasperPrint jasperPrint = jasperReportService.generateReport("classpath:/jasper/report.jrxml", parameters, data);
modelAndView = new ModelAndView(jasperReportsViewResolver);
modelAndView.addObject("jasperPrint", jasperPrint);
modelAndView.addObject("format", "pdf");
return modelAndView;
}
```
6.配置JasperReportService
创建JasperReportService来处理报表生成的逻辑。
```java
@Service
public class JasperReportService {
@Autowired
private JasperReportsProperties jasperReportsProperties;
public JasperPrint generateReport(String reportPath, Map<String, Object> parameters, List<Map<String, Object>> data) {
try {
JasperReport jasperReport = JasperCompileManager.compileReport(reportPath);
JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(data);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
return jasperPrint;
} catch (JRException e) {
throw new RuntimeException(e);
}
}
}
```
通过以上步骤,Spring Boot与JasperReports的整合就完成了。可以通过访问/report.pdf来生成报表。
阅读全文