Xceed Docx returns blank document

依然范特西╮ 提交于 2019-12-23 04:47:27

问题


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

please help


回答1:


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:

Before document.Save():

stream = [_________________________...]
ptr    =  ^

After calling document.Save():

stream = [<xml><p>my word document</p><p>the end</p></xml>_________________________...]
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    =                                                  ^   

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

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    =  ^

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


来源:https://stackoverflow.com/questions/50033523/xceed-docx-returns-blank-document

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!