根据模板导出word的util

导入freemarker依赖jar包,配置模板doc->xml->ftl,里面的数据转换成${name}这样,搞完一定要检查,以免转换错误,

public class WordExportUtil {


    /**
     * 配置信息,代码本身写的还是很可读的,就不过多注解了
     */
    private static Configuration configuration = null;
    /**
     * 这里注意的是利用WordExportUtil的类加载器动态获得模板文件的位置
     */
    private static final String templateFolder = WordExportUtil.class.getClassLoader().getResource("/").getPath();


    /**
     * @param response
     * @param map          文件对象
     * @param temSubFolder 模板所在resource子目录(web项目下)
     * @param templateName 模板名称
     * @throws IOException
     */
    public static void exportWord(HttpServletResponse response, Map<String, Object> map, String temSubFolder, String templateName, String newFileName) throws IOException {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        //数据装配
        configuration.setObjectWrapper(new DefaultObjectWrapper());
        //忽略null报错
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        configuration.setDirectoryForTemplateLoading(new File(templateFolder + "/" + temSubFolder));
        Template freemarkerTemplate = configuration.getTemplate(templateName + ".ftl");
        PrintWriter out = null;
        try {
            // 调用工具类的createDoc方法生成Word文档
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件名
            String fileName = newFileName + ".doc";
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
            out = response.getWriter();
            freemarkerTemplate.process(map, out);
        } catch (TemplateException e) {
            throw new CommonExcp(EnumExcp.INTERNAL_SERVER_ERROR.getCode(), "导出失败!");
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}

有问题找我,qq_1872515795

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要使用JavaPOI来根据模板导出Word,你需要进行以下步骤: 1. 首先,你需要准备好Word模板文件,它将包含一些占位符,用于在运行时将数据填充到模板中。 2. 然后,你需要使用JavaPOI来读取模板文件,并将其加载到内存中。 3. 接下来,你需要使用JavaPOI来查找并替换模板中的占位符。可以使用Apache POI中提供的XWPFDocument类来代表Word文档。 4. 最后,你需要使用JavaPOI将生成的Word文档保存到磁盘上。 下面是一个示例代码,它将读取一个Word模板文件,将占位符替换为实际数据,并将生成的文档保存到磁盘上: ```java import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.HashMap; import java.util.Map; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; public class WordTemplateExample { public static void main(String[] args) throws Exception { // Load the Word template file FileInputStream fis = new FileInputStream("template.docx"); XWPFDocument document = new XWPFDocument(fis); // Replace the placeholders with actual data Map<String, String> data = new HashMap<>(); data.put("name", "John Doe"); data.put("address", "123 Main St."); replacePlaceholders(document, data); // Save the generated Word document FileOutputStream fos = new FileOutputStream("output.docx"); document.write(fos); fos.close(); // Close the document document.close(); } private static void replacePlaceholders(XWPFDocument document, Map<String, String> data) { for (XWPFParagraph paragraph : document.getParagraphs()) { for (XWPFRun run : paragraph.getRuns()) { String text = run.getText(0); if (text != null) { for (Map.Entry<String, String> entry : data.entrySet()) { if (text.contains(entry.getKey())) { text = text.replace(entry.getKey(), entry.getValue()); run.setText(text, 0); } } } } } } } ``` 在这个示例中,我们定义了一个名为 `replacePlaceholders()` 的方法,它将查找并替换Word文档中的占位符。我们使用 `XWPFDocument` 类来代表Word文档,使用 `XWPFParagraph` 和 `XWPFRun` 来访问文档中的段落和文本内容。我们将占位符和实际数据存储在一个 `Map` 中,并使用 `replacePlaceholders()` 方法将占位符替换为实际数据。 请注意,这只是一个简单的示例,你需要根据自己的需求进行适当的修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值