java POI HTML转Word 两种方式

说明,不论使用哪种方式,都不能引用CSS来渲染样式,而是使用style,或者将样式放在当前页面的<style></style>中

方法一、

1、引用的jar包

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>4.1.0</version>
</dependency>

2、核心代码

String html = "<div>测试内容</div";

POIFSFileSystem poifs = null;
FileOutputStream ostream = null;
ByteArrayInputStream bais = null;
String uuid = "测试.doc";
File file = null;

try {
  //HTML内容必须被<html><body></body></html>包装
  fileParam.setcContent("<html><body>" + html + "</body></html>");
  byte[] b = fileParam.getcContent().getBytes();
  bais = new ByteArrayInputStream(b);
  poifs = new POIFSFileSystem();
  DirectoryEntry directory = poifs.getRoot();
  //WordDocument名称不允许修改
  directory.createDocument("WordDocument", bais);
  ostream = new FileOutputStream(uuid);
  poifs.writeFilesystem(ostream);//当前目录下就生成了一个测试.doc的文档
} catch (Exception e) {
  logger.error("exception is {}", e);
} finally {
  IOUtils.closeQuietly(poifs);
  IOUtils.closeQuietly(ostream);
  IOUtils.closeQuietly(bais);
  try {
    FileUtils.forceDelete(file);
  } catch (Exception e2) {
  }
}

 

方法二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
     * word格式html的标签头
     */
    public static final String HTML_TAG_BGN = "<html xmlns=\"http://www.w3.org/TR/REC-html40\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\"><head><meta name=\"ProgId\" content=\"Word.Document\" /><meta name=\"Generator\" content=\"Microsoft Word 12\" /><meta name=\"Originator\" content=\"Microsoft Word 12\" /> <!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View></w:WordDocument></xml><[endif]-->";
     
 
public filePath downloadWordReport(String htmlForPrint) {
        try {
            String wordString = htmlForPrint.replaceAll("<head>", "").replaceAll("<html>", HTML_TAG_BGN );
            String fileName = new String("测试文件.doc".getBytes(), "UTF-8");
            //上传文件方法
            return this.upload(new ByteArrayInputStream(wordString.getBytes()), fileName);
 
        } catch (Exception e) {
            return null;
        }
    }

  

posted @   介寒食  阅读(25918)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示