Xceed Docx返回空白文档 [英] Xceed Docx returns blank document
问题描述
在这里,我要使用xceed docx将报告导出为docx文件,但是它返回空白文档(空)
noob here, i want to export a report as docx file using the xceed docx, but it returns blank document (empty)
MemoryStream stream = new MemoryStream();
Xceed.Words.NET.DocX document = Xceed.Words.NET.DocX.Create(stream);
Xceed.Words.NET.Paragraph p = document.InsertParagraph();
p.Append("Hello World");
document.Save();
return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "DOCHK.docx");
请帮助
推荐答案
问题:
虽然您的数据已被写入MemoryStream
,但是内部的流指针"或游标(按照传统的术语,就像磁带头一样)位于数据的末尾书面:
The problem:
While your data has been written to the MemoryStream
, the internal "stream pointer" or cursor (in old-school terminology, think of it as like a tape-head) is at the end of the data you've written:
在document.Save()
之前:
stream = [_________________________...]
ptr = ^
致电document.Save()
后:
stream = [<xml><p>my word document</p><p>the end</p></xml>_________________________...]
ptr = ^
当您调用Controller.File( Stream, String )
时,它将继续从当前ptr
位置继续读取,因此仅读取空白数据:
When you call Controller.File( Stream, String )
it will then proceed to read on from the current ptr
location and so only read blank data:
stream = [<xml><p>my word document</p><p>the end</p></xml>from_this_point__________...]
ptr = ^
(实际上,它根本不会读取任何内容,因为MemoryStream
特别不允许读取超出其内部长度限制的内容,该长度默认为到目前为止已写入的数据量)
(In reality it won't read anything at all because MemoryStream
specifically does not allow reading beyond its internal length limit which by default is the amount of data written to it so far)
如果将ptr
重置为流的开头,那么当读取流时,返回的数据将从写入的数据的开头开始:
If you reset the ptr
to the start of the stream, then when the stream is read the returned data will start from the beginning of written data:
stream = [<xml><p>my word document</p><p>the end</p></xml>_________________________...]
ptr = ^
解决方案:
在从流中读取数据之前,您需要将MemoryStream重置为位置0:
Solution:
You need to reset the MemoryStream to position 0 before reading data from the stream:
using Xceed.Words.NET;
// ...
MemoryStream stream = new MemoryStream();
DocX document = DocX.Create( stream );
Paragraph p = document.InsertParagraph();
p.Append("Hello World");
document.Save();
stream.Seek( 0, SeekOrigin.Begin ); // or `Position = 0`.
return File( stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "DOCHK.docx" );
这篇关于Xceed Docx返回空白文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!