vb.net 如何在所需位置的现有 .docx 文件中添加文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21139450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:27:14  来源:igfitidea点击:

How to add a text in existing .docx file on desired location

vb.netms-word

提问by Dev

I want to open an existing .docx file and insert some text in second paragraph.

我想打开一个现有的 .docx 文件并在第二段中插入一些文本。

Private Sub insertText()
Dim WordApp As New Microsoft.Office.Interop.Word.Application
Dim aDoc As Microsoft.Office.Interop.Word.Document = WordApp.Documents.Open("C:\File1.docx")
Dim RNG As Microsoft.Office.Interop.Word.Range()

end sub

Now what should I write to insert some text in second para ?? Any help will be greatly appreciated. Thanks in advance.

现在我应该写什么来在第二段插入一些文本?任何帮助将不胜感激。提前致谢。

回答by JohnZaj

You can use Application.Selection.TypeText()for that:

你可以使用Application.Selection.TypeText()

 Private Sub insertText()
    Dim WordApp As New Microsoft.Office.Interop.Word.Application
    WordApp.Visible = True
    Dim aDoc As Microsoft.Office.Interop.Word.Document = WordApp.Documents.Open("C:\File1.docx")

    Dim paragraphs As Word.Paragraphs = aDoc.Paragraphs

    If (paragraphs.Count > 1) Then
        paragraphs(2).Range.Select()
        WordApp.Selection.TypeText("test")
    End If

    aDoc.Save()
    aDoc.Close()

    WordApp.Quit()
End Sub

You should probably close up the document then word safely so you don't have a winword.exe hanging after your program is finished ( I added this quick-and-dirty for you, but its not 100% foolproof)

您可能应该关闭文档然后安全地关闭 word,这样您的程序完成后就不会挂起 winword.exe(我为您添加了这个快速而肮脏的内容,但它不是 100% 万无一失)

Please excuse my poor, lazy vb.net style. If you like c sharp - note that c sharp since v4.0 is MUCH better than it used to be with Office Interop, and I recommend it.

请原谅我可怜的、懒惰的 vb.net 风格。如果您喜欢 c 锐利 - 请注意,自 v4.0 以来的 c 锐利比以前使用 Office Interop 好得多,我推荐它。

回答by Dev

Yes.. I got the answer..

是的..我得到了答案..

Private Sub insertText()
    Dim WordApp As New Microsoft.Office.Interop.Word.Application
    Dim aDoc As Microsoft.Office.Interop.Word.Document = WordApp.Documents.Open("C:\File1.docx")
    Dim RNG As Microsoft.Office.Interop.Word.Range()
    Dim PARA As Microsoft.Office.Interop.Word.Paragraph = aDoc.Paragraphs.Add()

    If aDoc.Paragraphs.Count > 1 Then
        aDoc.Paragraphs(2).Range.InsertParagraphBefore()
        aDoc.Paragraphs(2).Range.Text = "Hello World"
    end if
end sub

This code first a new para above second para and inserts Hello World in newly created second para. Cheers....

此代码首先在第二个段落上方添加一个新段落,然后在新创建的第二个段落中插入 Hello World。干杯....