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;
    }
相关推荐
Volunteer Technology1 天前
Sentinel的限流算法
java·python·算法
岁岁种桃花儿1 天前
SpringCloud从入门到上天:Nacos做微服务注册中心
java·spring cloud·微服务
jdyzzy1 天前
什么是 JIT 精益生产模式?它与传统的生产管控方式有何不同?
java·大数据·人工智能·jit
Chasmれ1 天前
Spring Boot 1.x(基于Spring 4)中使用Java 8实现Token
java·spring boot·spring
汤姆yu1 天前
2026基于springboot的在线招聘系统
java·spring boot·后端
计算机学姐1 天前
基于SpringBoot的校园社团管理系统
java·vue.js·spring boot·后端·spring·信息可视化·推荐算法
艾莉丝努力练剑1 天前
【Linux:文件】基础IO:文件操作的系统调用和库函数各个接口汇总及代码演示
linux·运维·服务器·c++·人工智能·centos·io
骆驼爱记录1 天前
Word样式库不显示的8种修复方法
word·wps·新人首发
java1234_小锋1 天前
Java高频面试题:SpringBoot如何自定义Starter?
java·spring boot·面试
落霞的思绪1 天前
Spring AI Alibaba 集成 Redis 向量数据库实现 RAG 与记忆功能
java·spring·rag·springai