java導出帶圖片的Word文檔(freemarker)帶圖片

1.首先新建一個帶圖片的doc

 

2.另存爲xml格式(具體看上一篇)

3.把生成的xml文件進行修改

4.修改後綴爲ftl,作爲模板文件使用,放到指定位置(我放到了電腦的D盤template文件夾中)

5.後臺填充數據

Map<String, Object> data = new HashMap<String, Object>(); //聲明map用來存數據

//將具體的數據存到map中,注意,這裏的key名稱要和模板文件的佔位符名稱一致
data.put("sfzh", "111111111111111111");

//這裏是處理圖片
//獲取項目的部署路徑(因爲我的圖片在服務器中)
		String realPath = request.getSession().getServletContext().getRealPath("/").replace(request.getContextPath().replaceAll("/", ""), ""); 
		String img = null;
        InputStream in;
        byte[] picdata = null;
        try {
//讀取圖片
            in = new FileInputStream(realPath+"images/rl/image_123.jpg");
            picdata = new byte[in.available()];
            in.read(picdata);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        img = encoder.encode(picdata);
		
		data.put("image", img);
		
        //參數解釋(第一個參數是模板文件的名稱,第二、三個拼成生成文件的名稱(這樣文件名就叫文檔名稱-文檔1.doc),第四個是數據map)
		WordUtil.word("rqpz.ftl", "文檔名稱", "文檔1", data);

6.另附WordUtil的源碼

public class WordUtil {
	public static void word(String ftl,String tb,String ryname,Map<String, Object> map) throws TemplateException, IOException{
		HttpServletResponse response = ServletActionContext.getResponse(); 
		response.reset(); 
		Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        //獲取模板所在的路徑
        configuration.setDirectoryForTemplateLoading(new File("D:/template/"));
        //以utf-8的編碼讀取ftl文件
        Template t =  configuration.getTemplate(ftl,"utf-8");
        String fileName = URLEncoder.encode(tb+"-"+ryname,"UTF-8") + ".doc";
        //1.設置文件ContentType類型,這樣設置,會自動判斷下載文件類型
        response.setContentType("multipart/form-data");
        //2.設置文件頭:最後一個參數是設置下載文件名
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        Writer out1 = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "utf-8"),10240);
        t.process(map, out1);
        out1.close();
	} 
	
}

 

發佈了67 篇原創文章 · 獲贊 14 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章