美文网首页全栈程序猿的成长
【springboot+easypoi】一行代码搞定简单的wor

【springboot+easypoi】一行代码搞定简单的wor

作者: 小尘哥 | 来源:发表于2018-08-08 08:57 被阅读110次

之前写过一篇《一行代码搞定Excel导入导出》,有需要的童鞋可以回头看一下,今天简单说一下怎么一行代码实现简单的word导出。有的童鞋不太同意了,扯淡呢一行代码。你说的对,不是一行,但是封装后每次调用的时候再看是什么情况。^_^

1、像之前一样的引入easypoi的pom

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

2、工具类封装

 /**
     * 导出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 {
            delAllFile(temDir);//这一步看具体需求,要不要删
        }

    }

3、调用测试

1.在项目下找个地方放模板文件

word.docx
2.确定临时生成文件的存放路径
3.controller调用(这里有我说的一行代码)
import com.df.commons.utils.FileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("demo")
public class TestController {

    @RequestMapping("export")
    public void export(HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> params = new HashMap<>();
        params.put("title","这是标题");
        params.put("name","李四");
        //这里是我说的一行代码
        FileUtil.exportWord("word/export.docx","F:/test","aaa.docx",params,request,response);
    }
}

4、模版格式

我只是这里写成了表格,你可以用任意格式,只需要替换变量即可。


模板.png
导出结果.png

相关文章

网友评论

  • 351b3dc22984:或者吧WordExportUtil()方法发一份也行:blush:
  • 351b3dc22984:谁有完整的demo,可以发我一份吗,谢谢
  • 5efe1cc7ceb4:@小尘哥 以模板为例,如果我让params.put("name","");了一个空的字符串,为什么导出的word相应位置为{{name}}而不是空白,这个是不支持这样吗,还是有特殊的写法。
    351b3dc22984:@小尘哥 大哥,急用,能不能发一份这个代码WordExportUtil()
    5efe1cc7ceb4:@小尘哥 谢谢,了解了。非常感谢。
    小尘哥:@呆萌小半夏 嗯,空字符串会解析不到,建议用个占位符,比如“-”
  • LeoChen_amazing:word导出报错:java.lang.NoSuchFieldError: RAW_XML_FILE_HEADER,求解答
    小尘哥:准备简信发给你呢,结果内容太长:disappointed_relieved:
    小尘哥:@小确幸_07bb public static boolean delAllFile(String path) {
    boolean flag = false;
    File file = new File(path);
    if (!file.exists()) {
    return flag;
    }
    if (!file.isDirectory()) {
    return flag;
    }
    String[] tempList = file.list();
    File temp = null;
    for (int i = 0; i < tempList.length; i++) {
    if (path.endsWith(File.separator)) {
    temp = new File(path + tempList[i]);
    } else {
    temp = new File(path + File.separator + tempList[i]);
    }
    if (temp.isFile()) {
    temp.delete();
    }
    if (temp.isDirectory()) {
    //先删除文件夹里面的文件
    delAllFile(path + File.separator + tempList[i]);
    //再删除空文件夹
    delFolder(path + File.separator + tempList[i]);
    flag = true;
    }
    }
    return flag;
    }

    public static void delFolder(String folderPath) {
    try {
    //删除完里面所有内容
    delAllFile(folderPath);
    String filePath = folderPath;
    File myFilePath = new File(filePath);
    myFilePath.delete(); //删除空文件夹
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
  • LeoChen_amazing:小尘哥您好,想请问一下delAllFile()方法中的代码能提供一下吗?感谢
    351b3dc22984:@小尘哥 谢谢了,已经解决过了
    小尘哥:@你亂了我的時光 这个包是easypoi带的,看一下第一步引的jar包
    351b3dc22984:有WordExportUtil()这个代码吗,可以发一下吗,谢谢了

本文标题:【springboot+easypoi】一行代码搞定简单的wor

本文链接:https://www.haomeiwen.com/subject/igqtbftx.html