springboot使用freemarker进行复杂Excel导出(多sheet页)
在Spring Boot中使用FreeMarker导出复杂的Excel文件(包含多个sheet页),你可以使用Apache POI库,它提供了操作Excel文件的接口。以下是一个简化的例子:
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
- 创建FreeMarker模板,例如
sheet1.ftl
和sheet2.ftl
,用于生成Excel的不同sheet页面的内容。 - 创建服务来处理Excel文件的生成:
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class ExcelExportService {
private Configuration freemarkerCfg;
public ExcelExportService(Configuration freemarkerCfg) {
this.freemarkerCfg = freemarkerCfg;
}
public void exportExcelWithMultipleSheets(String templatePath, String outputPath) throws IOException, TemplateException {
// 创建Workbook
Workbook workbook = new XSSFWorkbook();
// 创建数据模型
Map<String, Object> sheet1Data = new HashMap<>();
sheet1Data.put("data", getDataForSheet1());
Map<String, Object> sheet2Data = new HashMap<>();
sheet2Data.put("data", getDataForSheet2());
// 加载模板
Template sheet1Template = freemarkerCfg.getTemplate("sheet1.ftl");
Template sheet2Template = freemarkerCfg.getTemplate("sheet2.ftl");
// 创建Sheet
Sheet sheet1 = workbook.createSheet("Sheet1");
Sheet sheet2 = workbook.createSheet("Sheet2");
// 合并模板和数据生成内容
StringWriter sheet1Writer = new StringWriter();
sheet1Template.process(sheet1Data, sheet1Writer);
StringWriter sheet2Writer = new StringWriter();
sheet2Template.process(sheet2Data, sheet2Writer);
// 将内容写入Sheet
// ...
// 写入输出流
try (OutputStream outputStream = new FileOutputStream(outputPath)) {
workbook.write(outputStream);
}
// 关闭Workbook
workbook.close();
}
private Object getDataForSheet1() {
// 返回Sheet1的数据
return null;
}
private Object getDataForSheet2() {
// 返回Sheet2的数据
return null;
}
}
- 配置FreeMarker和ExcelExportService:
评论已关闭