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;
    }
相关推荐
HEJOO91 小时前
指针的算术运算详解
java·数据结构·算法
sunshine22 girl1 小时前
Java学习六 Java常见API-2--String-3-字符串的截取替换和其他方法
java·开发语言·学习
EatFan1 小时前
从“框架混战“到“运行时收敛“:2026 年 AI Agent 开发框架的三条路线之争
java·数据库·人工智能·多智能体·ai agent·mcp·agent 框架
小蒜学长1 小时前
基于SpringBoot的佳新超市管理系统设计与实现系统(代码+数据库+LW)
java·数据库·spring boot·后端·佳新超市管理系统
sunshine22 girl2 小时前
Java学习六 Java常见API-1-Radom随机数
java·开发语言·学习
wangbing11252 小时前
使用jps jstack排查系统问题
java
于指尖飞舞2 小时前
java面试题总结
java·开发语言
ZealSinger3 小时前
LangChain4j用AiServices拼Tool
java·rag·ai智能体·langchain4j
vx_Biye_Design3 小时前
springboot高校选课系统82776-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·spring·课程设计·express
weixin_448290253 小时前
书庐开发实战教学
javascript·css·html