freemarker匯出複雜樣式的Excel
阿新 • • 發佈:2019-08-25
freemarker匯出複雜樣式的Excel
程式碼地址:
gitee
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匯出做了相應的優化,有需要可以檢視對應文件
hutool
easyExcel