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を使用して作成する2番目の方法です。

 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);

2番目の方法で作成すると、生成されたドキュメントは適切ではありません。document.xmlには、xml宣言が表示されます。initialXmlは、初期WordMLxmlの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有効なデータだけでなく、バ​​ッファの余分な部分を返します。

通常、。を使用してxmlヘッダーを省略できますXmlWriterSettings

より直接的に書き込みを行うことはほぼ確実ですが、私は(電車の中で...)信号を使い果たしようとしています。

于 2010-05-12T15:55:56.800 に答える