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/