如何在 vb.net 核心中打开 Word 模板、更新一些文本并另存为 .pdf
How to open Word template, update some text, and save as .pdf in vb.net core
我正在开发一个 vb.net 核心控制台应用程序,该应用程序将数据库中的数据查询到数据表中,打开 Word (.dot) 模板文件,更新一些文本,然后另存为 .pdf 文件而不用保存对原始模板的更改。 Word 非常挑剔。在调试时,如果抛出异常,当我到达 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) 爆炸时的异常..
下面显示了如何在 .NET 控制台应用程序中使用 Word 互操作打开 .dot
(或 .dotx
)Word 模板,替换一些文本,然后导出(即:保存)它作为 PDF。为了进行测试,我使用了 .NET 6。
尝试以下操作:
添加引用:
- Microsoft Word xx.x 对象库(例如:Microsoft Word 16.0 对象库)
添加以下导入语句:
- 导入 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
注意:您可能希望return一个整数而不是一个字符串。
用法:
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
资源:
我正在开发一个 vb.net 核心控制台应用程序,该应用程序将数据库中的数据查询到数据表中,打开 Word (.dot) 模板文件,更新一些文本,然后另存为 .pdf 文件而不用保存对原始模板的更改。 Word 非常挑剔。在调试时,如果抛出异常,当我到达 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) 爆炸时的异常..
下面显示了如何在 .NET 控制台应用程序中使用 Word 互操作打开 .dot
(或 .dotx
)Word 模板,替换一些文本,然后导出(即:保存)它作为 PDF。为了进行测试,我使用了 .NET 6。
尝试以下操作:
添加引用:
- Microsoft Word xx.x 对象库(例如:Microsoft Word 16.0 对象库)
添加以下导入语句:
- 导入 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
注意:您可能希望return一个整数而不是一个字符串。
用法:
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
资源: