我有一個Word文檔存儲在我希望用作模板的服務器上。我需要用數據庫中的數據替換某些文本。使用模板生成Word文檔
我遇到的兩個問題是: 服務器上沒有辦公室使用Microsoft.Office.Interop,我無法將任何文檔保存到服務器。
我認爲我走在正確的軌道上,但不能拿出一個可行的解決方案。我想我的最佳途徑是讀入內存並使用字節數組來允許用戶保存文件。
我正在做這樣的事情,但我目前難住。
Dim path As String = HttpContext.Current.Request.PhysicalApplicationPath & "Letters\Test.docx"
Dim docBA As Byte() = File.ReadAllBytes(path)
Dim wordDoc As WordprocessingDocument = WordprocessingDocument.Open(path, True)
Using (wordDoc)
Dim docText As String = Nothing
Dim sr As StreamReader = New StreamReader(wordDoc.MainDocumentPart.GetStream)
Using (sr)
docText = sr.ReadToEnd
End Using
Dim regexText As Regex = New Regex("FIRST_NAME")
docText = regexText.Replace(docText, "TESTING!!!")
Dim sw As StreamWriter = New StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create))
Dim modBA As Byte()
Using (sw)
sw.Write(docText)
modBA = sw.Encoding.GetBytes(sw.BaseStream, 0, sw.BaseStream.Length)
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename= DownloadSample.docx")
HttpContext.Current.Response.ContentType = "application/octectstream"
HttpContext.Current.Response.BinaryWrite(modBA)
HttpContext.Current.Response.End()
End Using
我試過這樣一次,放棄了。由於.docx基本上是一個XML文檔,所以可以設想做一個XSLT(我有一些成功,但是太麻煩了,沒有用處)。*你可以*在服務器上有Office,但它不是線程安全的,所以你那裏也有麻煩。我的最終解決方案是將Word文檔轉換爲可填寫的PDF,在Post上將用戶的Web數據寫入FDF並在後端使用PDFTk以在運行時合併兩者。 – Duston