最近开发碰到一个导出word问题,导出内容涉及富文本。尝试了使用word模版书签插值的方式,不过不支持富文本;又尝试了Aspose.Words插件,的确好用,对富文本支持也比较好,奈何这玩意是收费的,使用破解版存在版权问题,随即考虑使用OpenXML方式解决。
实现代码如下:
/// <summary>
/// word下载
/// </summary>
/// <param name="fileName">下载文件路径</param>
/// <param name="title">标题</param>
/// <param name="body">内容</param>
public void WordDownload(string fileName, string title,string body)
{
using (WordprocessingDocument doc = WordprocessingDocument.Create(fileName, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
{
MainDocumentPart mainPart = doc.AddMainDocumentPart();
new Document(new Body()).Save(mainPart);
string altChunkId = "myId";
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes($"<html><head><meta charset=\"UTF-8\"><h1><center>{title}</center></h1></head><body>{body}</body></html>"));
AlternativeFormatImportPart formatImportPart = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId);
formatImportPart.FeedData(ms);
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
mainPart.Document.Body.Append(altChunk);
mainPart.Document.Save();
}
}
调用方式:
var title = "测试标题";
var body = "<p>测试内容啊啊啊啊啊啊啊啊啊啊啊</p><p>第二段内容啦啦啦啦啦啦啦啦</p>";
var savePath = @"d:\123\test.docx";
new BooksBll().WordDownload(savePath, title, body);
OpenXML功能还是很强大的,这种拼html标签的方式比较灵活,想要的Word文档样式都可以先在html里实现。