我有 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 而没有这个问题。