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

行っている変更は、閉じるまでdocMemoryStreamに反映されません。以下のように配置memdocdoc.Close()

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

問題を修正するとNewly inserted paragraph、の上部にテキストが表示されますTest2.docx

また、スニペットに必要な参照が1つありません。

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 に答える