OpenXML方式导出word

最近开发碰到一个导出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里实现。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据的流

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值