ASP.NET CORE OpenXml altChunk将许多文档合并到一个流中,不会合并所有文档

时间:2017-10-15 17:02:23

标签: c# asp.net-core

5个文档中只有一个会合并到流中。此过程完成,没有任何异常,并返回文档流。 来自Microsoft Word的错误消息是“Word找到不可读的内容。您要恢复此文档的内容吗?” 我是使用OpenXml的新手......我在想我的问题是使用altChunk

public IActionResult WordMergeStream()
    {
        //Create a stream and merge 5 word documents into the stream.
        //Use _hostingEnvironment context for Path
        string strWebRootPath = _hostingEnvironment.WebRootPath;
        //Use Memory Stream 
        var memoryStream = new MemoryStream();
        //there test five files
        string[] filepaths = new[] { @"/assets/Documents/Document1.docx", @"/assets/Documents/Document2.docx", @"/assets/Documents/Document3.docx", @"/assets/Documents/Document4.docx", @"/assets/Documents/Document5.docx" };
        for (int i = 0; i < filepaths.Length; i++)
            using (WordprocessingDocument myDocument = WordprocessingDocument.Create(memoryStream, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
            {
                string fn = @filepaths[i];
                MainDocumentPart myMainDocumentPart = myDocument.AddMainDocumentPart();
                new DocumentFormat.OpenXml.Wordprocessing.Document(new DocumentFormat.OpenXml.Wordprocessing.Body()).Save(myMainDocumentPart);
                //Create the Document Body and some sample text
                DocumentFormat.OpenXml.Wordprocessing.Body body = myMainDocumentPart.Document.Body;
                body.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(
                            new DocumentFormat.OpenXml.Wordprocessing.Run(
                                new DocumentFormat.OpenXml.Wordprocessing.Text("...Sample Text..."))));
                //Add the chunk
                string altChunkId = "AltChunkId" + i;
                AlternativeFormatImportPart chunk = myMainDocumentPart.AddAlternativeFormatImportPart(
                    AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                using (FileStream fileStream = new FileStream(strWebRootPath + @filepaths[i], FileMode.Open, FileAccess.Read))
                {
                    chunk.FeedData(fileStream);
                }
                DocumentFormat.OpenXml.Wordprocessing.AltChunk altChunk = new DocumentFormat.OpenXml.Wordprocessing.AltChunk() { Id = altChunkId };
                myMainDocumentPart.Document.Body.InsertAfter(altChunk, myMainDocumentPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Last());
                myMainDocumentPart.Document.Save();
                myDocument.Close();
        }
    string strFileDownloadName = "my.docx";
    memoryStream.Seek(0, SeekOrigin.Begin);
    return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document") { FileDownloadName = strFileDownloadName };

0 个答案:

没有答案