f# - 如何将 OpenXML SDK 与 F# 和 MemoryStreams 结合使用

标签 f# openxml

This article说在使用 OpenXML SDK 时需要使用可调整大小的 MemoryStreams,并且示例代码工作正常。

但是,当我将示例 C# 代码转换为 F# 时,文档保持不变:

open System.IO
open DocumentFormat.OpenXml.Packaging
open DocumentFormat.OpenXml.Wordprocessing

[<EntryPoint>]
let Main args =
    let byteArray = File.ReadAllBytes "Test.docx"

    use mem = new MemoryStream()
    mem.Write(byteArray, 0, (int)byteArray.Length)

    let para = new Paragraph()
    let run = new Run()
    let text = new Text("Newly inserted paragraph")
    run.InsertAt(text, 0) |> ignore
    para.InsertAt(run, 0) |> ignore

    use doc = WordprocessingDocument.Open(mem, true)
    doc.MainDocumentPart.Document.Body.InsertAt(para, 0) |> ignore

    // no change to the document
    use fs = new FileStream("Test2.docx", System.IO.FileMode.Create)
    mem.WriteTo(fs)

    0

当我使用 WordprocessingDocument.Open("Test1.docx", true) 时,它工作正常,但我想使用 MemoryStream。我做错了什么?

最佳答案

在关闭 doc 之前,您对 doc 所做的更改不会反射(reflect)在 MemoryStream mem 中。将 doc.Close() 放置如下

...
doc.MainDocumentPart.Document.Body.InsertAt(para, 0) |> ignore 
doc.Close()
...

解决了问题,您将在 Test2.docx 顶部看到文本新插入的段落

此外,您的代码片段缺少一个必需的引用:

open DocumentFormat.OpenXml.Packaging 

来自WindowsBase.dll

编辑:正如 ildjarn 指出的,更符合 F# 习惯的重构是以下重构:

open System.IO
open System.IO.Packaging
open DocumentFormat.OpenXml.Packaging 
open DocumentFormat.OpenXml.Wordprocessing 

[<EntryPoint>] 
let Main args = 
    let byteArray = File.ReadAllBytes "Test.docx" 

    use mem = new MemoryStream() 
    mem.Write(byteArray, 0, (int)byteArray.Length) 

    do
        use doc = WordprocessingDocument.Open(mem, true) 
        let para = new Paragraph() 
        let run = new Run() 
        let text = new Text("Newly inserted paragraph") 
        run.InsertAt(text, 0) |> ignore     
        para.InsertAt(run, 0) |> ignore
        doc.MainDocumentPart.Document.Body.InsertAt(para, 0) |> ignore 

    use fs = new FileStream("Test2.docx", FileMode.Create) 
    mem.WriteTo(fs) 

    0 

关于f# - 如何将 OpenXML SDK 与 F# 和 MemoryStreams 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10701885/

相关文章:

openxml - 如何在 Excel 工作表 OpenXML 2.0 C# 中创建图表/图形

f# - 函数的名称,如 Option.bind,当输入为 None 时返回 Some(x)

visual-studio-2013 - 如何制作在 VS2010/VS2013-preview 上同样工作的 F# 项目?

f# - F#可以重构为pointfree风格吗?

asynchronous - 等待取消异步工作流

.net - 轻松创建/更新 Office Open XML 图表(首选 PowerPoint)

c# - 为什么.NET OpenXML SDK 的 SpreadsheetDocument.Open() 方法会抛出 NullReferenceException?

f# - Windows IoT 开发人员计划是否支持 F#

algorithm - 从 Excel 导入中查找包含的边界区域

php - 如何在 HTML/PHP 中显示格式化的 Word 文档?