You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DocumentFormat.OpenXml 无法将Word文档保存到内存流问题求助

解决OpenXml保存到MemoryStream为空的问题

问题出在WordprocessingDocument的资源释放时机:当你在wordDocument的using块未结束时就读取MemoryStream,此时文档的最终内容还未完全写入流中——WordprocessingDocument会在Dispose(using块结束时自动触发)时完成所有的流写入操作。

修改后的代码

public Task<byte[]> ConvertToWordAsync(string text)
{
    if (string.IsNullOrEmpty(text))
        return Task.FromResult(Array.Empty<byte>());

    using var memoryStream = new MemoryStream();
    
    // 单独的using块处理WordprocessingDocument,确保Dispose后再读取流
    using (var wordDocument = WordprocessingDocument.Create(memoryStream, WordprocessingDocumentType.Document))
    {
        MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
        mainPart.Document = new Document
        {
            Body = new Body()
        };
        Body body = mainPart.Document.Body;
        Paragraph paragraph = new Paragraph();
        Run run = new Run();
        Text bodyText = new Text(text);
        run.Append(bodyText);
        paragraph.Append(run);
        body.Append(paragraph);

        wordDocument.Save();
    }
    // 此时wordDocument已Dispose,所有内容已写入memoryStream
    
    // 重置流位置(ToArray()本身会返回全部内容,此步骤可选,但更严谨)
    memoryStream.Position = 0;
    return Task.FromResult(memoryStream.ToArray());
}

关键原因说明

  • 当使用本地文件路径时,WordprocessingDocument会实时将内容写入磁盘,所以文件能正常生成;但使用MemoryStream时,部分缓冲内容仅在Dispose阶段才会被flush到流中。
  • 将wordDocument的using块独立,确保在读取memoryStream前,文档资源已被正确释放,所有内容都已写入流内。

注:原代码中的text.IsNullOrEmpty()若为自定义扩展方法可保留,标准库中需改为string.IsNullOrEmpty(text)。

内容的提问来源于stack exchange,提问作者Alexandre Sobral Martins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 19:05:18