JAVA exports word documents based on templates through EasyPoi

1. Introduce dependencies

备注:如果没有jar包冲突,可以忽略jar排重(<exclusions>标签内内容)

 <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.3.0</version>
            <exclusions>
                <exclusion>
                    <artifactId>poi-ooxml-schemas</artifactId>
                    <groupId>org.apache.poi</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>guava</artifactId>
                    <groupId>com.google.guava</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.3.0</version>
            <exclusions>
                <exclusion>
                    <artifactId>guava</artifactId>
                    <groupId>com.google.guava</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.3.0</version>
        </dependency>

2. word template

3. Specific code

3.1controller layer

@GetMapping(value = "/exportReportPreview")
public void exportReportPreview(HttpServletRequest request, HttpServletResponse response, @RequestParam String no) throws IOException {
    accidentService.exportReportPreview(request, response, no);
}

3.2 Implementation class

@Override 
public void exportReportPreview(HttpServletRequest request, HttpServletResponse response, String no) throws IOException { 

   Accident accident = this.getAccidentByNo(no); 

//★★★★★★★★The template is stored in the resources directory, the specific directory is determined by your own needs Create //"template/docx/accident/first report.docx" 
//fileSavePath is a temporary directory (local testing is the path under a certain drive letter, and the Linux server is the specific path) 
    //word template address 
    TemplateExportParams templateExportParams = new TemplateExportParams( "template/docx/accident/first report.docx"); 
    String wordModelPath = templateExportParams.getTemplateUrl(); 
    //Generate temporary file address 
    Map<String,Object> params = JSON.parseObject(JSON.toJSONString(accident), Map. class); 
    ExportWordUtil.exportWord(wordModelPath,fileSavePath,accident.getTitle() + ".docx",params,request,response);

}

3.3 Tools

@Slf4j 
public class ExportWordUtil { 
    /** 
     * Export word 
     * <p>The first step is to generate the replaced word file, which only supports docx</p> 
     * <p>The second step is to download the generated file</p> 
     * < p>The third step is to delete the generated temporary files</p> 
     * Variable format in template variables: { 
   
   {foo}} 
     * @param templatePath word template address 
     * @param temDir Generate temporary file storage address 
     * @param fileName file name 
     * @ param params Replaced parameters 
     * @param request HttpServletRequest 
     * @param response HttpServletResponse 
     */ 
    public static void exportWord(String templatePath, String temDir, String fileName, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) { 
        Assert.notNull( templatePath,"Template path cannot be empty");
        Assert.notNull(temDir,"The temporary file path cannot be empty"); 
        Assert.notNull(fileName,"The export file name cannot be empty"); 
        Assert.isTrue(fileName.endsWith(".docx"),"Word export please Use docx format"); 
        if (!temDir.endsWith("/")){ 
            temDir = temDir + File.separator; 
        } 
        File dir = new File(temDir); 
        if (!dir.exists()) { 
            dir.mkdirs (); 
        } 
        try { 
            String userAgent = request.getHeader("user-agent").toLowerCase(); 
            if (userAgent.contains("msie") || userAgent.contains("like gecko")) { 
                fileName = URLEncoder .encode(fileName,"UTF-8");
            } else { 
                fileName = new String (fileName.getBytes("utf-8"),"ISO-8859-1");
            }
            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params); 

            String tmpPath = temDir + fileName; 
            FileOutputStream fos = new FileOutputStream(tmpPath); 
            doc.write(fos); 
            // Set forced download not to open 
            response.setContentType("application/force -download"); 
            // Set the file name 
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName); 
            OutputStream out = response.getOutputStream(); 
            doc.write(out); 
            out.close( ); 
        } catch (Exception e) {
            e.printStackTrace(); 
        } 
        finally { 
            //This step depends on the specific needs, whether to delete 
            delFileWord(temDir,fileName); 
        } 
    } 

    public static void exportWord(String templatePath, String temDir, String fileName, List<Map<String, Object >> params, HttpServletRequest request, HttpServletResponse response) { 
        Assert.notNull(templatePath,"The template path cannot be empty"); 
        Assert.notNull(temDir,"The temporary file path cannot be empty"); 
        Assert.notNull(fileName,"Export The file name cannot be empty"); 
        Assert.isTrue(fileName.endsWith(".docx"),"Please use docx format for word export"); 
        if (!temDir.endsWith("/")){ 
            temDir = temDir + File .separator;
        } 
        File dir = new File(temDir); 
        if (!dir.exists() ) { 
            dir.mkdirs();
        }
        try {
            String userAgent = request.getHeader("user-agent").toLowerCase();
            if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
            }
            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);

            String tmpPath = temDir + fileName;
            FileOutputStream fos = new FileOutputStream(tmpPath);
            doc.write(fos);
            // 设置强制下载不打开
            response.setContentType("application/force-download"); 
            // Set the file name 
    public static void delFileWord(String filePath, String fileName){
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName); 
            OutputStream out = response.getOutputStream(); 
            doc.write(out); 
            out.close(); 
        } catch (Exception e) { 
            e .printStackTrace(); 
        } 
        finally { 
            //This step depends on the specific requirements, whether to delete 
            delFileWord(temDir,fileName); 
        } 
    } 

    /** 
     * Delete the file generated at zero time 
     */ 
        File file =new File(filePath+fileName) ; 
        File file1 =new File(filePath); 
        file.delete(); 
        file1.delete(); 
    } 
}

Guess you like

Origin blog.csdn.net/weixin_43005845/article/details/123706071