【问题标题】:OpenXml create word document and downloadOpenXml 创建word文档并下载
【发布时间】:2016-09-26 06:45:45
【问题描述】:

我刚刚开始探索 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!” 但是当我下载文件时,文件是空的

我错过了什么? 提示

【问题讨论】:

    标签: c# asp.net-mvc openxml


    【解决方案1】:

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

    您的 OpenXml 文件的文件扩展名和内容类型也不正确,但这通常不会导致您遇到所遇到的问题。

    完整的代码清单应该是:

    var stream = new MemoryStream();
    using (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();
    
        //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");
    

    【讨论】:

      【解决方案2】:

      我认为您必须在返回之前将流位置设置为 0,例如:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多