加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – OpenXml创建word文档并下载

发布时间:2020-12-15 23:31:53 所属栏目:百科 来源:网络整理
导读:我刚刚开始探索OpenXml,我正在尝试创建一个新的简单word文档,然后下载该文件 这是我的代码 [HttpPost] public ActionResult WordExport() { var stream = new MemoryStream(); WordprocessingDocument doc = WordprocessingDocument.Create(stream,DocumentF
我刚刚开始探索OpenXml,我正在尝试创建一个新的简单word文档,然后下载该文件

这是我的代码

[HttpPost]
        public ActionResult WordExport()
        {
            var stream = new MemoryStream();
            WordprocessingDocument doc = WordprocessingDocument.Create(stream,DocumentFormat.OpenXml.WordprocessingDocumentType.Document,true);

            MainDocumentPart mainPart = doc.AddMainDocumentPart();

            new Document(new Body()).Save(mainPart);

            Body body = mainPart.Document.Body;
            body.Append(new Paragraph(
                        new Run(
                            new Text("Hello World!"))));

            mainPart.Document.Save();


            return File(stream,"application/msword","test.doc");


        }

我原以为它会包含’Hello World!’
但是当我下载文件时,文件是空的

我错过了什么?
TKS

解决方法

你似乎有两个主要问题.首先,您需要在WordprocessingDocument上调用Close方法,以便保存一些文档部分.最简单的方法是在WordprocessingDocument周围使用using语句.这将导致为您调用Close方法.其次,你需要寻找流的开头,否则你将获得一个空的结果.

您还有一个OpenXml文件的文件扩展名和内容类型不正确,但这通常不会导致您遇到的问题.

完整的代码清单应该是:

var stream = new MemoryStream();
using (WordprocessingDocument doc = WordprocessingDocument.Create(stream,true))
{
    MainDocumentPart mainPart = doc.AddMainDocumentPart();

    new Document(new Body()).Save(mainPart);

    Body body = mainPart.Document.Body;
    body.Append(new Paragraph(
                new Run(
                    new Text("Hello World!"))));

    mainPart.Document.Save();

    //if you don't use the using you should close the WordprocessingDocument here
    //doc.Close();
}
stream.Seek(0,SeekOrigin.Begin);

return File(stream,"application/vnd.openxmlformats-officedocument.wordprocessingml.document","test.docx");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读