1

我有 2 个代码片段,它们的工作方式不同

using (WordprocessingDocument wordDocument =
           WordprocessingDocument.Create(@"D:\Tests\WordML\ML_Example.docx", WordprocessingDocumentType.Document))
        {
            // Add a main document part. 
            MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
            TextReader tr = new StreamReader("SimpleTextExample.xml");
            mainPart.Document = new Document(tr.ReadToEnd());
        }

在这里它工作得很好并且生成 .docx 很好。

现在用字节和 MemoryStream-uri 制作它的第二种方法。

 MemoryStream modeleRootStream = new MemoryStream();

XmlWriterSettings writerSettings = new XmlWriterSettings { OmitXmlDeclaration = true }; XmlWriter xmlWriter = XmlWriter.Create(modeleRootStream, writerSettings);

        initialXml.WriteTo(xmlWriter);

        xmlWriter.Flush();

        modeleRootStream.Position = 0;
       MemoryStream streamWithWord = new MemoryStream();

        using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(streamWithWord,
            WordprocessingDocumentType.Document))
        {
            // Add a main document part. 
            MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

            string streamContent = string.Empty;

            using (StreamReader reader = new StreamReader(modeleRootStream))
            {
               streamContent = reader.ReadToEnd();
            }

            mainPart.Document = new Document(streamContent);
        }

        byte[] wordDocBytes = streamWithWord.GetBuffer();

        streamWithWord.Close();

        File.WriteAllBytes(@"D:\Tests\WordML\ML_Example1.docx", wordDocBytes);

当您使用第二种方式时,生成的文档并不好。在它的 document.xml 中,你会看到 xml 声明。initialXml 表示初始 WordML xml 的 XElement。

<?xml version="1.0" encoding="utf-8"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">

……

当您尝试在 Word 中打开它时,它会提示您文件被截断。

我怎样才能使用字节和 MemoryStreams 而没有这个问题。

4

1 回答 1

1

这是错误的:

byte[] wordDocBytes = streamWithWord.GetBuffer();

那应该是:

byte[] wordDocBytes = streamWithWord.ToArray();

GetBuffer返回缓冲区的额外部分 - 不仅仅是有效数据。

您通常可以省略带有XmlWriterSettings.

几乎可以肯定的是更直接地进行写入,但我即将用完信号(在火车上......)。

于 2010-05-12T15:55:56.800 回答