Java POI 導出帶有圖片的word


  1. 引入maven ,具體可以上github看一下,這里做簡單的說明,是一個大神封裝了一下

官方提供的語法

文本語法是 {{Text}} 

圖片語法是{{@Image}}

其他的自己去看官方文檔

<!--github一個處理word的一個解決方案 https://github.com/Sayi/poi-tl-->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.0.0</version>
</dependency>


  2. 准備模板

 

 3.代碼演示

 

Map<String, Object> data = new HashMap<String, Object>();
// 姓名
data.put("name", "祁貢策");
// 性別
data.put("sex", "女");
// 頭像 photoPath 為頭像的地址
 data.put("photo", new PictureRenderData(127, 185, photoPath));
// 其他屬性代碼都省略
// 寫入word輸出

        try {
            ClassPathResource template = new ClassPathResource("word/appointDismiss.docx");
            String filePath = template.getFile().getPath();
            XWPFTemplate xwpfTemplate = XWPFTemplate.compile(filePath)
                    .render(data);
        
        String docName = DateUtil.DateToString(new Date(), DateStyle.YYYYMMDDHHMMSS) + ".docx";
File targetFile = new File(docName);
            FileOutputStream out = new FileOutputStream(targetFile);
            xwpfTemplate.write(out);
            out.flush();
            out.close();
            xwpfTemplate.close();
            // 下載輸出到瀏覽器
            FileUtil.downFile(request,response,docName,targetFile);
            FileUtil.deleteDir(targetFile.getPath());
        } catch (Exception e) {
            log.info("文件生成失敗:"+e.getMessage());
            throw new DataNotFoundException("文件生成失敗:"+e.getMessage());
        }

 

  /**
     * 下載文件到瀏覽器
     * @param request
     * @param response
     * @param filename 要下載的文件名
     * @param file     需要下載的文件對象
     * @throws IOException
     */
    public static void downFile(HttpServletRequest request, HttpServletResponse response, String filename, File file) throws IOException {
        //  文件存在才下載
        if (file.exists()) {
            OutputStream out = null;
            FileInputStream in = null;
            try {
                // 1.讀取要下載的內容
                in = new FileInputStream(file);

                // 2. 告訴瀏覽器下載的方式以及一些設置
                // 解決文件名亂碼問題,獲取瀏覽器類型,轉換對應文件名編碼格式,IE要求文件名必須是utf-8, firefo要求是iso-8859-1編碼
                String agent = request.getHeader("user-agent");
                if (agent.contains("FireFox")) {
                    filename = new String(filename.getBytes("UTF-8"), "iso-8859-1");
                } else {
                    filename = URLEncoder.encode(filename, "UTF-8");
                }
                // 設置下載文件的mineType,告訴瀏覽器下載文件類型
                String mineType = request.getServletContext().getMimeType(filename);
                response.setContentType(mineType);
                // 設置一個響應頭,無論是否被瀏覽器解析,都下載
                response.setHeader("Content-disposition", "attachment; filename=" + filename);
                // 將要下載的文件內容通過輸出流寫到瀏覽器
                out = response.getOutputStream();
                int len = 0;
                byte[] buffer = new byte[1024];
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            }
        }
    }
    /**
     * 遞歸刪除目錄下的所有文件及子目錄下所有文件
     *
     * @param filePath 將要刪除的文件目錄路徑
     * @return boolean Returns "true" if all deletions were successful.
     * If a deletion fails, the method stops attempting to
     * delete and returns "false".
     */
    public static boolean deleteDir(String filePath) {
        File dir = new File(filePath);
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //遞歸刪除目錄中的子目錄下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(filePath + File.separator + children[i]);
                if (!success) {
                    return false;
                }
            }
        }
        // 目錄此時為空,可以刪除
        return dir.delete();
    }

 

結果:

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM