1. 程式人生 > >freemarker匯出含圖片的word

freemarker匯出含圖片的word

匯入依賴包:

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.23</version>
</dependency>

將要匯出的實體類表:

新建匯出模板的word文件,插入一張隨機圖片:

將word文件另存為xml格式並用編輯器開啟,將其中的base64字串替換為需要插入的欄位${imgUrl},儲存為person.xml作為模板:

程式碼:

    public String exportWord(){
        Person person = personDao.getPerson(13);
        Map<String,Object> maps = new HashMap<String,Object>();
        maps.put("name",person.getName());
        maps.put("country",person.getCountry());
        maps.put("imgUrl",GetImageStrFromUrl(person.getImgUrl()));
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        try {
            configuration.setDirectoryForTemplateLoading(new File("E:/doc"));
            File outFile = new File("E:/doc/test.doc");
            Template t = configuration.getTemplate("person.xml", "utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(outFile), "utf-8"), 10240);
            t.process(maps, out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }

        return "匯出成功";
    }
//base64轉化工具
   public static String GetImageStrFromUrl(String imgURL) {

        byte[] data=null;
        try {
            // 建立URL
            URL url = new URL(imgURL);
            // 建立連結
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            //超時響應時間為5秒
            conn.setConnectTimeout(5 * 1000);
            //通過輸入流獲取圖片資料
            InputStream inStream = conn.getInputStream();
            //得到圖片的二進位制資料,以二進位制封裝得到資料,具有通用性
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            //建立一個Buffer字串
            byte[] buffer = new byte[1024];
            //每次讀取的字串長度,如果為-1,代表全部讀取完畢
            int len = 0;
            //使用一個輸入流從buffer裡把資料讀取出來
            while ((len = inStream.read(buffer)) != -1) {
                //用輸出流往buffer裡寫入資料,中間引數代表從哪個位置開始讀,len代表讀取的長度
                outStream.write(buffer, 0, len);
            }
            //關閉輸入流
            inStream.close();
            data = outStream.toByteArray();
            BASE64Encoder encoder = new BASE64Encoder();
            // 返回Base64編碼過的位元組陣列字串
            //System.out.println(encoder.encode(data));
            return encoder.encode(data);
        } catch (IOException e) {
            e.printStackTrace();
            return "";

        }
        // 對位元組陣列Base64編碼

    }

執行結果: