1. 程式人生 > 程式設計 >freemarker模板動態生成word檔案

freemarker模板動態生成word檔案

前言

使用freemarker模板動態匯出word檔案

準備

  • 環境

    • IntellJ IDEA 2018.2
    • SringBoot 2.1.9
  • 版本

    • Word 2003 .doc 格式
    • spring-boot-starter-freemarker 2.1.9

簡單模板準備

<一> word 2003 新建.doc 模板

簡單模板

<二> 另存為.xml 檔案,格式化程式碼,並檢查是否存在變數分離問題,如圖

error

調整後

true

<三> 重新命名為.ftl模板freemarker檔案

ftl檔案

Springboot匯出簡單word

使用freemarker模板引擎

  		<dependency
>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> 複製程式碼

配置freemarker

  #    設定freemarker
  freemarker:
    allow-request-override: false
    #    開發過程建議關閉快取
    cache: true
check-template-location: false charset: UTF-8 content-type: text/html; charset=utf-8 expose-request-attributes: false expose-session-attributes: false expose-spring-macro-helpers: false request-context-attribute: # 預設字尾就是.ftl suffix: .ftl template-loader-path:
classPath:/templates/code/ 複製程式碼

將模板UserInfo.flt檔案放入專案

import

測試Controller程式碼

    @PostMapping("user/doc")
    @ResponseBody
    @ApiOperation(value="匯出使用者doc",httpMethod = "POST",produces="application/json",notes = "匯出使用者doc")
    public ResultBean exportDoc() throws  IOException{
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(this.getClass(),"/templates/code");
        Template template = configuration.getTemplate("UserInfo.ftl");
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("name","gaolei");
        dataMap.put("id","02201");
        dataMap.put("code","251525v");
        dataMap.put("pwd","root");
        dataMap.put("tel","08583552");
        File outFile = new File("UserInfoTest.doc");
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
        try {
            template.process(dataMap,out);
            out.flush();
            out.close();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return ResultBean.success();
    }
複製程式碼

Swagger測試

swagger

預設儲存在專案根目錄

path

資料成功匯出得到word

資料檢視

複雜模板word匯出

模板準備

操作同上,模板如下

複雜模板

Controller測試

	@PostMapping("user/requireInfo")
    @ResponseBody
    @ApiOperation(value="匯出使用者確認資訊表doc",notes = "匯出使用者確認資訊表doc")
    public ResultBean  userRequireInfo() throws  IOException{
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(this.getClass(),"/templates/code");
        Template template = configuration.getTemplate("need.ftl");
        Map<String,Object> resultMap = new HashMap<>();
        List<UserInfo> userInfoList = new ArrayList<>();
        userInfoList.add(new UserInfo("2019","安全環保處質量安全科2608室","風險研判","9:30","10:30","風險研判原型設計","參照甘肅分公司提交的分析研判表,各個二級單位維護自己的風險研判資訊,需要一個簡單的風險上報流程,各個二級單位可以看到所有的分析研判資訊作為一個知識成果共享。","張三","李四"));
        resultMap.put("userInfoList",userInfoList);
        File outFile = new File("userRequireInfo.doc");
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
        try {
            template.process(resultMap,out);
            out.flush();
            out.close();
            return null;
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return ResultBean.success();
    }
複製程式碼

freemarker 遍歷

	<#list userInfoList as user>
			獲取值:${user.name} 
        	...
    </#list>
複製程式碼

遍歷資料

匯出效果

資料展示

匯出帶圖片Word

模板準備

模板帶圖

Controller

 @PostMapping("user/exportPic")
    @ResponseBody
    @ApiOperation(value="匯出帶圖片的Word",notes = "匯出帶圖片的Word")
    public ResultBean exportPic() throws IOException {
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(this.getClass(),"/templates/code");
        Template template = configuration.getTemplate("userPic.ftl");
        Map<String,Object> map = new HashMap<>();
        map.put("name","gaolei");
        map.put("date","2015-10-12");
        map.put("imgCode",imageToString());
        File outFile = new File("userWithPicture.doc");
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
        try {
            template.process(map,out);
            out.flush();
            out.close();
            return null;
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return  ResultBean.success();
    }

    public static String imageToString() {
        String imgFile = "E:\\gitee\\excel-poi\\src\\main\\resources\\static\\img\\a.png";
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String imageCodeBase64 =  Base64Utils.encodeToString(data);

        return imageCodeBase64;
    }
複製程式碼

Swagger測試

swagger

匯出效果

效果

demo原始碼

詳情見github 倉庫