springboot POI报表案例生成HTML
时间: 2023-10-12 21:15:07 浏览: 42
可以使用POI和Freemarker来生成HTML格式的报表。
首先,需要使用POI来读取Excel文件中的数据,并将数据存储到Java对象中。然后,使用Freemarker来生成HTML模板,并将Java对象中的数据填充到模板中。最后,将生成的HTML文件输出到指定的目录中。
以下是一个简单的示例代码:
1. 读取Excel文件并将数据存储到Java对象中
```java
public class ExcelReader {
public static List<Report> readExcel(String filePath) throws IOException {
List<Report> reportList = new ArrayList<>();
FileInputStream inputStream = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
Report report = new Report();
report.setName(row.getCell(0).getStringCellValue());
report.setValue(row.getCell(1).getNumericCellValue());
reportList.add(report);
}
workbook.close();
inputStream.close();
return reportList;
}
}
```
2. 使用Freemarker生成HTML模板
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Report</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<#list reportList as report>
<tr>
<td>${report.name}</td>
<td>${report.value}</td>
</tr>
</#list>
</tbody>
</table>
</body>
</html>
```
3. 填充数据并输出HTML文件
```java
public class ReportGenerator {
public static void generateReport(List<Report> reportList, String htmlFilePath) throws IOException, TemplateException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
cfg.setClassForTemplateLoading(ReportGenerator.class, "/templates/");
cfg.setDefaultEncoding("UTF-8");
Template template = cfg.getTemplate("report.ftl");
Map<String, List<Report>> data = new HashMap<>();
data.put("reportList", reportList);
File htmlFile = new File(htmlFilePath);
Writer out = new FileWriter(htmlFile);
template.process(data, out);
out.close();
}
}
```
在以上示例代码中,`Report`类是一个简单的Java类,用来存储Excel文件中的数据,`report.ftl`是HTML模板文件,`ReportGenerator`类用来将数据填充到模板中,并输出HTML文件。
需要注意的是,需要将`report.ftl`文件放到`/templates/`目录下,以便`Freemarker`能够正确地加载模板文件。
最后,可以使用以下代码来调用以上示例代码:
```java
public class Application {
public static void main(String[] args) throws IOException, TemplateException {
List<Report> reportList = ExcelReader.readExcel("report.xlsx");
ReportGenerator.generateReport(reportList, "report.html");
}
}
```
以上就是使用POI和Freemarker来生成HTML格式的报表的示例代码。