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

时间:2016-08-05 23:22:30

标签: vb.net visual-studio-2010 ms-word

任何人都可以教我如何使用vb代码从Microsoft Word获取文本吗?

1 个答案:

答案 0 :(得分:0)

这是一个简单函数的测试示例,用于在给定文件路径的情况下从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"和#34; Imports System.IO"在本代码的代码开头需要编译。