easypoi基于模板导出word文档

1.在pom.xml中添加easypoi依赖

		<!-- easypoi -->
		 <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.2.0</version>
        </dependency>

2.创建导出word文档的工具类

import cn.afterturn.easypoi.word.WordExportUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;


public class ExportWordUtils {

	 /**
     * 导出word
     * <p>第一步生成替换后的word文件,只支持docx</p>
     * <p>第二步下载生成的文件</p>
     * <p>第三步删除生成的临时文件</p>
     *   模版变量中变量格式:{{foo}}
     * @param templatePath word模板地址
     * @param temDir 生成临时文件存放地址
     * @param fileName 文件名
     * @param params 替换的参数
     * @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,"模板路径不能为空");
        Assert.notNull(temDir,"临时文件路径不能为空");
        Assert.notNull(fileName,"导出文件名不能为空");
        Assert.isTrue(fileName.endsWith(".docx"),"word导出请使用docx格式");
        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");
            // 设置文件名
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            OutputStream out = response.getOutputStream();
            doc.write(out);
            out.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            delFileWord(temDir,fileName);//这一步看具体需求,要不要删
        }
    }
    
    /**
     * 删除零时生成的文件
     */
    public static void delFileWord(String filePath, String fileName){
        File file =new File(filePath+fileName);
        File file1 =new File(filePath);
        file.delete();
        file1.delete();
    }

}

3.添加word模板
在resources目录下的创建word目录,创建名为export.docx的模板文件放到resources/word目录下
在这里插入图片描述
4.在controller中添加调用方法

    @ApiOperation(value="导出word",notes="导出word",tags= {"导出word"})
    @RequestMapping(value="/exportWord",method=RequestMethod.GET)
    public void export(HttpServletRequest request, HttpServletResponse response, String planMonth, String projectCode){
    	//文件名
    	String fileName = planMonth+"技改项目管理月报.docx";
    	//标题
    	QueryWrapper projectTypeWrapper = new QueryWrapper();
    	projectTypeWrapper.eq("project_code", projectCode);
    	List<BaseProjectType> baseProjectTypeList = baseProjectTypeService.list(projectTypeWrapper);
    	String title = baseProjectTypeList.get(0).getProjectName();
    	//报告日期
    	String reportTime =  DateUtils.convert2String(new Date(), "yyyy年M月dd日");
    	
    	int year = DateUtils.getYear(DateUtils.convert2Date(planMonth+"-01", "yyyy-MM-dd"));
    	int month = DateUtils.getMonth(DateUtils.convert2Date(planMonth+"-01", "yyyy-MM-dd"));
    	//报告期间
    	String reportStartTime = DateUtils.convert2String(DateUtils.convert2Date(DateUtils.getFirstDayOfMonth(year, month), "yyyy-MM-dd"), "yyyy年M月dd日");
    	String reportEndTime = DateUtils.convert2String(DateUtils.convert2Date(DateUtils.getLastDayOfMonth(year, month), "yyyy-MM-dd"), "yyyy年M月dd日");
    	
        Map<String,Object> params = new HashMap<>();
        params.put("title",title);
        params.put("reportStartTime", reportStartTime);
        params.put("reportEndTime", reportEndTime);
        params.put("reportTime",reportTime);
       
        ExportWordUtils.exportWord("word/export.docx","D:/test",fileName,params,request,response);

    }

5.在vue前端添加导出按钮,点击执行导出功能

 <el-button type="primary" @click="doExport">导出</el-button>
    // 导出
    doExport() {
      if (this.filters.planMonth === undefined || this.filters.planMonth === '') {
        this.$message({ type: 'info', message: '请选择计划月份!' })
        return
      }
      if (this.filters.projectCode === undefined || this.filters.projectCode === '') {
        this.$message({ type: 'info', message: '请选择项目类型!' })
        return
      }
      window.open(this.baseUrl + '/monthlyWorkArrangeMx/exportWord?planMonth=' + this.filters.planMonth + '&projectCode=' + this.filters.projectCode)
    },
发布了23 篇原创文章 · 获赞 2 · 访问量 4246

猜你喜欢

转载自blog.csdn.net/weixin_45616483/article/details/102691865
今日推荐