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;
    }
相关推荐
ywl4708120877 分钟前
jwt生产token,简单版helloworld
java·数据库·spring
未若君雅裁12 分钟前
生产问题排查与性能瓶颈定位:日志、监控、链路追踪、压测与Arthas
java·web安全
器灵科技19 分钟前
AI视频工具实测:Seedance/可灵/HappyHorse谁最能打?
java·运维·数据库·人工智能·github
南部余额31 分钟前
RabbitMQ 进阶:延迟队列完全指南
java·分布式·spring·rabbitmq
phltxy33 分钟前
Spring AI Agents 智能体模式实战
java·人工智能·spring
摇滚侠42 分钟前
MyBatis 入门到项目实战 特殊 SQL 的执行 34-37
java·sql·mybatis
phltxy1 小时前
Spring AI 可观测性与 Zipkin 实战
java·人工智能·spring
兰令水1 小时前
leecodecode【面试150】【2026.6.13打卡-java版本】
java·算法·leetcode
TA远方1 小时前
【HTML】JavaScript Canvas 图像截取与保存完整指南
前端·javascript·html·canvas·截图·截取
.道阻且长.1 小时前
C++ string 操作指南:接口解析
java·c语言·开发语言·c++