2

本文说使用 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. 我究竟做错了什么?

4

1 回答 1

4

在您关闭之前,您所做的更改doc不会反映在 MemoryStream 中。放置如下memdocdoc.Close()

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

解决了问题,您将Newly inserted paragraphTest2.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 
于 2012-05-22T16:44:37.127 回答