easypoi导出word文档

导出word文档


#引入easypoi依赖

       <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.4.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.4.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.1</version>
        </dependency>

#创建导出工具类


import cn.afterturn.easypoi.word.WordExportUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;


public class ExportWordUtil {
    /**
     * 根据模板导出Word
     * @param response
     * @param map	替换参数值
     * @param modelFileName  文档模版存放路径
     * @param outFileName  输出文件名称
     */
    public static void exportWordByModel(HttpServletResponse response, Map<String, Object> map, String modelFileName, String outFileName) {
        try {
            // 1.获取模板文件路径 - 重点
            //XWPFDocument word = WordExportUtil.exportWord07(modelFileName, map);
//            String templatePath = filePath(modelFileName).getAbsolutePath();
            //直接传文件地址
            String templatePath = modelFileName;

            // 打印出模板文件的完整路径 - 校验路径是否存在
            File templateFile = new File(templatePath);

            if (templateFile.exists()) {
                System.out.println("模板文件存在: " + templateFile.getAbsolutePath());
            } else {
                System.out.println("模板文件不存在: " + templateFile.getAbsolutePath());
            }
            // 2.映射模板,替换数据
            XWPFDocument word = WordExportUtil.exportWord07(templatePath, map);
            // 3.设置返回参数的字符集
            response.reset();
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("application/msexcel");
            response.setContentType("text/html; charset=UTF-8");
            // 4.设置响应类型为Word文档
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            // 5.中文文件名处理,否则报错
            String encodedFileName = URLEncoder.encode(outFileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName + ".docx");
            // 6.将Word文档发送到浏览器
            word.write(response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据文件名获取文件对象
     * @param modelFileName
     * @return
     */
    public static File filePath(String modelFileName) {
        // 获取类加载器
        ClassLoader classLoader = ExportWordUtil.class.getClassLoader();
        // 尝试从类路径中加载资源
        URL resource = classLoader.getResource(modelFileName);
        return new File(resource.getFile());
    }
}

在需要调用导出的地方,直接使用工具类进行导出

    public void export(HttpServletResponse response) {
        //1. 先逻辑处理,查询出需要导出的数据,这里测试先写死

        //2.将需导出的数据,转为map键值方式
        Map<String,Object> map = new HashMap<>();
        map.put("year","2024");
        map.put("text","测试导出");
        map.put("month", "5");
        map.put("list", new ArrayList<>());//如果是表格方式导出,用集合
        ExportWordUtil.exportWordByModel(response,map,uploadPath+"/template.docx", String.valueOf(System.currentTimeMillis()));
    }

注:模版文档中需用{{year}}、{{text}}、{{date}}方式做占位符
在这里插入图片描述

前端调用接口后会在浏览器中,自动下载替换参数后的文档。
效果如下:
在这里插入图片描述

使用 EasyPoi 导出 Word 文档需要进行以下步骤: 1. 引入 EasyPoi 依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>5.2.0</version> </dependency> ``` 2. 创建模板 在 Word 文档中创建一个需要填充数据的模板,可以使用 Word 编辑器创建一个包含标签的文档。标签可以在文档中使用 ${} 表示。 例如,创建一个包含用户信息的模板,可以在 Word 文档中添加以下内容: ``` 姓名:${name} 年龄:${age} ``` 3. 创建数据源 创建一个 Java 类,包含需要导出的数据,例如: ```java public class User { private String name; private int age; // 省略 getter 和 setter 方法 } ``` 4. 使用 EasyPoi 导出 Word 文档 在 Java 代码中使用 EasyPoi 提供的 API 将数据填充到模板中,并将生成的 Word 文档保存到本地磁盘。例如: ```java // 创建模板对象 XWPFTemplate template = XWPFTemplate.compile("template.docx").render(data); // 将数据填充到模板中 Map<String, Object> data = new HashMap<>(); data.put("name", "张三"); data.put("age", 18); // 导出 Word 文档 try (FileOutputStream out = new FileOutputStream("output.docx")) { template.write(out); } template.close(); ``` 上述代码中,XWPFTemplate.compile("template.docx") 表示创建一个模板对象,template.render(data) 表示将数据填充到模板中,FileOutputStream("output.docx") 表示将生成的 Word 文档保存到本地磁盘。 以上就是使用 EasyPoi 导出 Word 文档的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值