如何使用 vb 将 word 文档中的文本转换为字符串?

How to get text from word document into a string using vb?

谁能教我如何使用 vb 代码从 Microsoft Word 中获取文本?

这是一个简单函数的测试示例,该函数根据文件路径return word 文档中的文本,希望对您有所帮助:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim docfilepath As String = "C:\Users\sooho\Desktop\test.docx"
    Dim doctext As String = getDocText(docfilepath)
    If doctext IsNot Nothing Then MsgBox(doctext)
    Me.Close()
End Sub
Private Function getDocText(ByVal filepath As String) As String
    If File.Exists(filepath) AndAlso Path.GetExtension(filepath).ToUpper.Equals(".DOCX") Then
        Dim app As Application = New Application
        Dim doc As Document = app.Documents.Open(filepath)
        Dim doctxt As String = doc.Content.Text
        app.Quit()
        Return doctxt
    Else
        Return Nothing
    End If
End Function

编辑:忘记提及,您需要在项目设置中添加 Microsoft.Office.Interop.Word 框架作为参考,这是与任何 Word 文档交互所必需的,除非您使用的是第三方库。此外,未显示,为了编译此示例,代码开头需要 "Imports Microsoft.Office.Interop.Word" 和 "Imports System.IO"。