動作が異なる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を使用して、この問題を回避するにはどうすればよいですか。