【问题标题】:Streaming Word Doc in OpenXML SDK using ASP.NET MVC 4 gets corrupt document使用 ASP.NET MVC 4 在 OpenXML SDK 中流式传输 Word Doc 会导致文档损坏
【发布时间】:2012-12-14 03:34:50
【问题描述】:

我正在尝试在 ASP.NET MVC 4 上执行此操作:

MemoryStream mem = new MemoryStream();
        using (WordprocessingDocument wordDoc =
            WordprocessingDocument.Create(mem, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
        {
            // instantiate the members of the hierarchy
            Document doc = new Document();
            Body body = new Body();
            Paragraph para = new Paragraph();
            Run run = new Run();
            Text text = new Text() { Text = "The OpenXML SDK rocks!" };

            // put the hierarchy together
            run.Append(text);
            para.Append(run);
            body.Append(para);
            doc.Append(body);

            //wordDoc.Close();

            ///wordDoc.Save();
        }


return File(mem.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ABC.docx");

但是 ABC.docx 以损坏的形式打开,即使修复后也无法打开。

有什么想法吗?

链接问题:

Streaming In Memory Word Document using OpenXML SDK w/ASP.NET results in "corrupt" document

【问题讨论】:

    标签: asp.net-mvc ms-word openxml-sdk


    【解决方案1】:

    显然问题来自缺少这 2 行:

    wordDoc.AddMainDocumentPart();
    wordDoc.MainDocumentPart.Document = doc;
    

    将代码更新到下面,它现在可以完美运行,即使不需要任何额外的刷新等。

    MemoryStream mem = new MemoryStream();
            using (WordprocessingDocument wordDoc =
                WordprocessingDocument.Create(mem, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
            {
                wordDoc.AddMainDocumentPart();
                // instantiate the members of the hierarchy
                Document doc = new Document();
                Body body = new Body();
                Paragraph para = new Paragraph();
                Run run = new Run();
                Text text = new Text() { Text = "The OpenXML SDK rocks!" };
    
                // put the hierarchy together
                run.Append(text);
                para.Append(run);
                body.Append(para);
                doc.Append(body);
                wordDoc.MainDocumentPart.Document = doc;
                wordDoc.Close();
            }
    return File(mem.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ABC.docx");
    

    【讨论】:

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