Java Html转Word

java 复制代码
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.*;

/**
     * Html转Word
     * @author hjj
     */
    public static MultipartFile htmlToWord(String html,String filePath)  throws Exception {
        // 1.生成文件名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = filePath+"/"+"LangChain" + sdf.format(new Date())+".doc";
        // 返回MyltipartFile类
        MultipartFile multipartFile = null;
        if (StringUtils.isNotEmpty(html)) {
            // 2.创建一个新的文档
            XWPFDocument document = new XWPFDocument();
            // 3.创建段落并添加文本内容
            XWPFParagraph paragraph = document.createParagraph();
            XWPFRun run = paragraph.createRun();
            run.setText(html);
            // 4.保存文档到文件
            try (FileOutputStream out = new FileOutputStream(fileName)) {
                document.write(out);
                System.out.println("成功创建doc文件!");
                // 关闭流
                out.close();
                document.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 5.获取文件信息 Get File information
            File tempFile = new File(fileName);
            // 6.Create a FileInputStream from the file
            FileInputStream input = new FileInputStream(tempFile);
            // 7.Create a MultipartFile using MockMultipartFile
            multipartFile = new MockMultipartFile(
                    "file",
                    tempFile.getName(),
                    "application/msword",
                    input
            );

        }
        return multipartFile;
    }
相关推荐
若水不如远方4 小时前
Netty的四种零拷贝机制:深入原理与实战指南
java·netty
用户7493636848434 小时前
【开箱即用】一分钟使用java对接海外大模型gpt等对话模型,实现打字机效果
java
SimonKing5 小时前
一键开启!Spring Boot 的这些「魔法开关」@Enable*,你用对了吗?
java·后端·程序员
间彧5 小时前
Spring Boot集成Spring Security 6.x完整指南
java
xiezhr6 小时前
用户只需要知道「怎么办」,不需要知道「为什么炸了」
java·api·接口设计规范
xiezhr6 小时前
接口设计18条军规:写给那些半夜被“502”叫醒的人
java·api·restful
RainbowSea15 小时前
12. LangChain4j + 向量数据库操作详细说明
java·langchain·ai编程
RainbowSea15 小时前
11. LangChain4j + Tools(Function Calling)的使用详细说明
java·langchain·ai编程
考虑考虑19 小时前
Jpa使用union all
java·spring boot·后端
用户37215742613520 小时前
Java 实现 Excel 与 TXT 文本高效互转
java