【问题标题】:Xceed Docx returns blank documentXceed Docx 返回空白文档
【发布时间】:2018-10-06 14:16:15
【问题描述】:

这里是菜鸟,我想使用 xceed docx 将报告导出为 docx 文件,但它返回空白文档(空)

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

请帮忙

【问题讨论】:

    标签: c# .net docx xceed


    【解决方案1】:

    问题:

    虽然您的数据已写入MemoryStream,但内部“流指针”或游标(在老式术语中,将其视为磁带头)位于您已写入数据的末尾写:

    document.Save()之前:

    stream = [_________________________...]
    ptr    =  ^
    

    拨打document.Save()后:

    stream = [<xml><p>my word document</p><p>the end</p></xml>_________________________...]
    ptr    =                                                  ^
    

    当您调用Controller.File( Stream, String ) 时,它将继续从当前ptr 位置继续读取,因此只读取空白数据:

    stream = [<xml><p>my word document</p><p>the end</p></xml>from_this_point__________...]
    ptr    =                                                  ^   
    

    (实际上它根本不会读取任何内容,因为MemoryStream 特别不允许读取超出其内部长度限制,默认情况下是到目前为止写入它的数据量)

    如果您将ptr 重置为流的开头,则读取流时返回的数据将从写入数据的开头开始:

    stream = [<xml><p>my word document</p><p>the end</p></xml>_________________________...]
    ptr    =  ^
    

    解决方案:

    在从流中读取数据之前,您需要将 MemoryStream 重置为位置 0:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-19
      • 2018-10-12
      • 2018-09-18
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 2018-12-23
      相关资源
      最近更新 更多