如何不本地存储即可将HTML文本转换为Word Doc并输出字节流
方案解答
完全可以实现,全程操作均可在内存中完成,不需要写入本地磁盘。
核心逻辑是所有主流Word生成库都支持直接输出到内存流,不需要绑定本地文件路径,以下是不同常用开发语言的实现示例:
C# 实现
使用DocumentFormat.OpenXml官方库或开源NPOI库即可,示例代码:
using System.IO; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; // htmlStr为存储HTML内容的字符串变量 string htmlStr = "你的HTML内容"; byte[] docBytes; using (MemoryStream ms = new MemoryStream()) { // 直接在内存流中创建Word文档 using (WordprocessingDocument doc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = doc.AddMainDocumentPart(); mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); // 若需要保留HTML的富文本样式,可搭配HtmlToOpenXml工具类解析后写入,全程无磁盘操作 run.AppendChild(new Text(htmlStr)); doc.Save(); } // 直接获取最终DOCX的字节流,可直接传给目标服务器 docBytes = ms.ToArray(); }
Java 实现
使用Apache POI库即可,示例代码:
import org.apache.poi.xwpf.usermodel.*; import java.io.ByteArrayOutputStream; // htmlStr为存储HTML内容的字符串变量 String htmlStr = "你的HTML内容"; byte[] docBytes; try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); XWPFDocument document = new XWPFDocument()) { XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); // 若需要解析HTML富文本样式,可搭配jsoup或POI自带的HTML解析工具处理 run.setText(htmlStr); document.write(outputStream); docBytes = outputStream.toByteArray(); }
Python 实现
使用python-docx库即可,示例代码:
from io import BytesIO from docx import Document # html_str为存储HTML内容的字符串变量 html_str = "你的HTML内容" doc = Document() # 若需要保留HTML富文本样式,可搭配mammoth等HTML解析工具处理后写入 doc.add_paragraph(html_str) byte_stream = BytesIO() doc.save(byte_stream) # 直接获取字节流,可直接传给目标服务器 doc_bytes = byte_stream.getvalue()
注意:如果需要完整保留HTML的样式(列表、图片、字体格式等),仅需替换上述示例中HTML转Word文档对象的解析逻辑即可,所有解析、生成操作都在内存中完成,不会触发任何本地磁盘写入操作。
内容的提问来源于stack exchange,提问作者Akbar Badhusha
相关产品推荐
相关产品推荐

