freemarker導出復雜樣式的Excel
代碼地址:
https://gitee.com/suveng/demo/tree/master/chapter.002
代碼存放於demo下面的chapter.002目錄下, 每個模塊都是獨立開的springboot應用,可以直接運行 application
環境
- springboot 2.1.2
- Freemarker 2.3.28
- JDK1.8
步驟
1.找到對應Excel模板
我在網上找了一網站下載了一個Excel模板, 地址
下載的文件是2018庫存表
2.Excel模板導出為xml格式
將其導出為xml格式;直接文件另存為即可
刪除多余的數據, 將模板變量填進去, 這個變量是需要符合 freemarker 的變量規則的;
具體內容可參考文件
3.替換freemarker變量
關鍵修改:
<#list products as product>
<Row>
<Cell>
<Data ss:Type="String">${product.name!}</Data>
</Cell>
<Cell>
<Data ss:Type="String">${product.number!}</Data>
</Cell>
<Cell>
<Data ss:Type="String">${product.type!}</Data>
</Cell>
<Cell>
<Data ss:Type="String">${product.unit!}</Data>
</Cell>
<Cell>
<Data ss:Type="String">${product.left!}</Data>
</Cell>
<Cell>
<Data ss:Type="String">${product.monthNumber!}</Data>
</Cell>
<Cell>
<Data ss:Type="String">${product.in!}</Data>
</Cell>
<Cell>
<Data ss:Type="String">${product.out!}</Data>
</Cell>
<Cell ss:StyleID="s54">
<Data ss:Type="String">${product.date?string('yyyy/MM/dd')}</Data>
</Cell>
</Row>
</#list>
自己可以拿到文件,對比一下.
具體 freemarker 語法, 可參考 鏈接
4.編寫代碼,變量替換
這里我使用我自己的腳手架,其實也是一個快速啟動的服務端程序,使用的是springboot構建的.有興趣可以過去看看鏈接
這里編寫web接口: 導出模板Excel
這里的數據是自己模擬的,隨機生成的無意義數據,使用了hutool工具包的randomUtil
AppController.java
@Controller
public class AppController {
@Autowired
private Configuration configuration;
@RequestMapping("/export")
public void export(HttpServletResponse response) throws Exception {
//自己封裝號數據實體
ArrayList<Product> products = new ArrayList<>();
//構造數據
for (int i = 0; i < 100; i++) {
Product e = new Product();
e.setName(RandomUtil.randomString(5));
e.setNumber(RandomUtil.randomString(2));
e.setOut(RandomUtil.randomString(2));
e.setIn(RandomUtil.randomString(2));
e.setType(RandomUtil.randomString(5));
e.setUnit(RandomUtil.randomString(4));
e.setMonthNumber(RandomUtil.randomString(1));
e.setDate(new Date());
products.add(e);
}
HashMap<String, Object> map = new HashMap<>();
map.put("products", products);
//構造輸出流
Template template = configuration.getTemplate("2018庫存表.xml", "UTF-8");
String fileName = "/data/files/" + DateUtil.now() + ".xlsx";
File file = new File(fileName);
FileWriter out = new FileWriter(fileName);
//變量替換
template.process(map, out);
//將文件輸出到response,返回給客戶端
FileInputStream in = new FileInputStream(file);
byte[] buffer = new byte[in.available()];
in.read(buffer);
in.close();
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=file.xlsx");
ServletOutputStream outputStream = response.getOutputStream();
response.setContentType("application/octet-stream");
outputStream.write(buffer);
outputStream.flush();
outputStream.close();
}
}
5. 結果展示
存在問題
- 變量替換,耗費CPU和內存並未經過測試,與POI這些組件相比到底哪個更好,這里存在疑問?
這里只是用作復雜樣式的Excel數據導出,並不適合用作大量數據導出.hutool工具包中和easyExcel都是針對大量數據的Excel導出做了相應的優化,有需要可以查看對應文檔