我正在開發一個 vb.net 核心控制臺應用程式,該應用程式將資料庫中的資料查詢到 DataTable 中,打開一個 Word (.dot) 模板檔案,更新一些文本,然后另存為 .pdf 而不保存對原始模板的更改。詞很挑剔。在除錯時,如果拋出例外,當我到達 catch 塊時 Word.Application 已經消失了,所以我似乎無法正常退出,并且顯然在記憶體中維護了一個實體,因為我必須重新啟動我的機器讓程式再次運行,因為 Word 無法啟動。
有沒有更好的方式與 Word 互動?
這是我的代碼:
Dim application As Word.Application = Nothing
Try
application = New Word.Application With {.Visible = True}
application.Documents.Open("C:\MattsFunctionReport.dot")
Dim document = application.ActiveDocument
'There are lots of these Items, just showing one as an example.
If IsDBNull(row.Item("FunctionName"))
document.Content.Find.Execute(FindText:="<<FunctionName>>", ReplaceWith:="", Replace:=WdReplace.wdReplaceAll)
Else
document.Content.Find.Execute(FindText:="<<FunctionName>>", ReplaceWith:=row.Item("FunctionName"), Replace:=WdReplace.wdReplaceAll)
End If
'save as PDF
application.ActiveDocument.SaveAs2("C:\SampleOutput.pdf", WdSaveFormat.wdFormatPDF)
'Close the document.
application.Documents.Close(WdSaveOptions.wdDoNotSaveChanges)
'Quit Word.Application
application.Quit()
Catch ex As Exception
'Close Word
application.Documents.Close(WdSaveOptions.wdDoNotSaveChanges)
application.Quit()
'Show Exception
ConsoleEx.WriteError(ex.Message)
ConsoleEx.WriteLineInRed(ex.StackTrace)
'Log Exception
WriteLog(ex.ToString)
Console.Writeline("Press any key to exit the program.")
Console.ReadKey()
End
End Try
這是我嘗試在不重新啟動的情況下再次除錯時遇到的例外。

這是 application.ActiveDocument.SaveAs("C:\SampleOutput.pdf", WdSaveFormat.wdFormatPDF) 爆炸時的例外。

uj5u.com熱心網友回復:
下面展示了如何在 .NET 控制臺應用程式中使用 Word 互操作打開.dot(或.dotx)Word 模板,替換一些文本,然后將其匯出(即:保存)為 PDF。為了測驗,我使用了 .NET 6。
嘗試以下操作:
添加參考:
- Microsoft Word xx.x 物件庫(例如:Microsoft Word 16.0 物件庫)
添加以下 Imports 陳述句:
- 匯入 Word = Microsoft.Office.Interop.Word
修改WordDoc:
Private Function ModifyWordDoc(filename As String, pdfFilename As String, Optional isVisible As Boolean = False) As String
Dim wordApp As Word.Application = Nothing
Dim document As Word.Document = Nothing
Try
'create new instance
wordApp = New Word.Application() With {.Visible = isVisible}
'create new document from template
document = wordApp.Documents.Add(Template:=filename)
'ToDo: add desired code
document.Content.Find.Execute(FindText:="<<FunctionName>>", ReplaceWith:="TEST", Replace:=Word.WdReplace.wdReplaceAll)
'export (ie: save) as PDF
document.ExportAsFixedFormat(pdfFilename, Word.WdExportFormat.wdExportFormatPDF)
Return "Successfully completed"
Catch ex As Exception
'ToDo: add desired code
Debug.WriteLine($"Error (ModifyWordDoc) - {ex.Message}")
Finally
If document IsNot Nothing Then
document.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
End If
If wordApp IsNot Nothing Then
wordApp.Quit()
End If
End Try
Return "Unsuccessful"
End Function
注意:您可能希望回傳整數而不是字串。
用法:
Sub Main(args As String())
Dim filename As String = "C:\Temp\Test.dot"
Dim pdfFilename As String = "C:\Temp\Test.pdf"
Console.WriteLine($"Modifying Word document '{filename}'...")
Dim result As String = ModifyWordDoc(filename, pdfFilename, True)
Debug.WriteLine($"result: {result}")
If result = "Successfully completed" Then
Environment.Exit(0)
Else
Environment.Exit(-1)
End If
End Sub
資源:
- Microsoft.Office.Interop.Word 命名空間
- Documents.Add(Object, Object, Object, Object) 方法
- Document.ExportAsFixedFormat 方法
- WdExportFormat 列舉
- 通過使用VB net自動列印pdf而不顯示對話框
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/455665.html
