richardwzp

利用 Visual Basic .NET 使 Word 自动新建文档

HOW TO:利用 Visual Basic .NET 使 Word 自动新建文档

文章编号 : 316383
最后修改 : 2007年1月17日
修订 : 8.1

概要

本文分步介绍如何利用 Visual Basic .NET 的自动化功能在 Word 中创建新文档。

代码示例

本文中的代码示例将说明如何完成以下任务:
插入包含文本和格式的段落。
浏览和修改文档中的不同范围。
插入表格、设置表格格式并在表格中填充数据。
添加图表。
要利用 Visual Basic .NET 的自动化功能创建新的 Word 文档,请执行以下步骤:
1. 启动 Microsoft Visual Studio .NET。在文件菜单上,单击新建,然后单击项目。在属性类型下单击 Visual Basic 项目,然后单击模板下的 Windows 应用程序。默认情况下会创建 Form1。
2. 添加对 Microsoft Word 对象库的引用。为此,请按照下列步骤操作:
a. 项目菜单上,单击添加引用
b. COM 选项卡上,找到 Microsoft Word 对象库并单击选择

注意 Microsoft Office 2003 包括 Primary Interop Assemblies (PIA)。Microsoft Office XP 不包括 PIA,但您可以下载 PIA。 有关 Office XP PIA 的其他信息,请单击下面的文章编号,以查看 Microsoft 知识库中相应的文章:
328912 (http://support.microsoft.com/kb/328912/EN-US/) INFO:Microsoft Office XP PIA 可供下载
c. 添加引用对话框中单击确定以接受您的选择。如果系统提示您为选定的库生成包装,请单击
3. 视图菜单上,选择工具箱以显示工具箱,然后向 Form1 添加一个按钮。
4. 双击 Button1。出现该窗体的代码窗口。
5. 在代码窗口中,将以下代码
    Private Sub Button1_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button1.Click
            End Sub
            
替换为:
    Private Sub Button1_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button1.Click
            Dim oWord As Word.Application
            Dim oDoc As Word.Document
            Dim oTable As Word.Table
            Dim oPara1 As Word.Paragraph, oPara2 As Word.Paragraph
            Dim oPara3 As Word.Paragraph, oPara4 As Word.Paragraph
            Dim oRng As Word.Range
            Dim oShape As Word.InlineShape
            Dim oChart As Object
            Dim Pos As Double
            'Start Word and open the document template.
            oWord = CreateObject("Word.Application")
            oWord.Visible = True
            oDoc = oWord.Documents.Add
            'Insert a paragraph at the beginning of the document.
            oPara1 = oDoc.Content.Paragraphs.Add
            oPara1.Range.Text = "Heading 1"
            oPara1.Range.Font.Bold = True
            oPara1.Format.SpaceAfter = 24    '24 pt spacing after paragraph.
            oPara1.Range.InsertParagraphAfter()
            'Insert a paragraph at the end of the document.
            '** \endofdoc is a predefined bookmark.
            oPara2 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range)
            oPara2.Range.Text = "Heading 2"
            oPara2.Format.SpaceAfter = 6
            oPara2.Range.InsertParagraphAfter()
            'Insert another paragraph.
            oPara3 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range)
            oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:"
            oPara3.Range.Font.Bold = False
            oPara3.Format.SpaceAfter = 24
            oPara3.Range.InsertParagraphAfter()
            'Insert a 3 x 5 table, fill it with data, and make the first row
            'bold and italic.
            Dim r As Integer, c As Integer
            oTable = oDoc.Tables.Add(oDoc.Bookmarks.Item("\endofdoc").Range, 3, 5)
            oTable.Range.ParagraphFormat.SpaceAfter = 6
            For r = 1 To 3
            For c = 1 To 5
            oTable.Cell(r, c).Range.Text = "r" & r & "c" & c
            Next
            Next
            oTable.Rows.Item(1).Range.Font.Bold = True
            oTable.Rows.Item(1).Range.Font.Italic = True
            'Add some text after the table.
            'oTable.Range.InsertParagraphAfter()
            oPara4 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range)
            oPara4.Range.InsertParagraphBefore()
            oPara4.Range.Text = "And here's another table:"
            oPara4.Format.SpaceAfter = 24
            oPara4.Range.InsertParagraphAfter()
            'Insert a 5 x 2 table, fill it with data, and change the column widths.
            oTable = oDoc.Tables.Add(oDoc.Bookmarks.Item("\endofdoc").Range, 5, 2)
            oTable.Range.ParagraphFormat.SpaceAfter = 6
            For r = 1 To 5
            For c = 1 To 2
            oTable.Cell(r, c).Range.Text = "r" & r & "c" & c
            Next
            Next
            oTable.Columns.Item(1).Width = oWord.InchesToPoints(2)   'Change width of columns 1 & 2
            oTable.Columns.Item(2).Width = oWord.InchesToPoints(3)
            'Keep inserting text. When you get to 7 inches from top of the
            'document, insert a hard page break.
            Pos = oWord.InchesToPoints(7)
            oDoc.Bookmarks.Item("\endofdoc").Range.InsertParagraphAfter()
            Do
            oRng = oDoc.Bookmarks.Item("\endofdoc").Range
            oRng.ParagraphFormat.SpaceAfter = 6
            oRng.InsertAfter("A line of text")
            oRng.InsertParagraphAfter()
            Loop While Pos >= oRng.Information(Word.WdInformation.wdVerticalPositionRelativeToPage)
            oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
            oRng.InsertBreak(Word.WdBreakType.wdPageBreak)
            oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
            oRng.InsertAfter("We're now on page 2. Here's my chart:")
            oRng.InsertParagraphAfter()
            'Insert a chart and change the chart.
            oShape = oDoc.Bookmarks.Item("\endofdoc").Range.InlineShapes.AddOLEObject( _
            ClassType:="MSGraph.Chart.8", FileName _
            :="", LinkToFile:=False, DisplayAsIcon:=False)
            oChart = oShape.OLEFormat.Object
            oChart.charttype = 4 'xlLine = 4
            oChart.Application.Update()
            oChart.Application.Quit()
            'If desired, you can proceed from here using the Microsoft Graph
            'Object model on the oChart object to make additional changes to the
            'chart.
            oShape.Width = oWord.InchesToPoints(6.25)
            oShape.Height = oWord.InchesToPoints(3.57)
            'Add text after the chart.
            oRng = oDoc.Bookmarks.Item("\endofdoc").Range
            oRng.InsertParagraphAfter()
            oRng.InsertAfter("THE END.")
            'All done. Close this form.
            Me.Close()
            End Sub
            
6. 将以下代码添加到 Form1.vb 的顶部:
Imports Word = Microsoft.Office.Interop.Word
            
7. 按 F5 键生成并运行程序。
代码完成后,请检查为您创建的文档。该文档包含两页设置了格式的段落、表格和图表。

使用模板

如果您要使用自动化功能来创建一些全部采用一种共用格式的文档,则利用基于预设格式的模板的新文档来开始创建过程会更加容易。与从头创建文档相比,将某个模板与 Word 自动化客户端配合使用有两大优点:
您可以对整个文档中的对象的格式设置和布局施加更多控制。
可以使用较少的代码创建文档。
通过使用模板,可以精确地调整表格、段落和其他对象在文档中的布局,并可为这些对象添加格式设置。通过使用自动化功能,可以基于包含下面这样的代码的模板创建新文档:
oWord.Documents.Add "<Path to your template>\MyTemplate.dot"
在模板中,可以定义书签,这样,自动化客户端就可以在文档的特定位置加入可变文本,如下所示:
oDoc.Bookmarks.Item("MyBookmark").Range.Text = "Some Text Here"
使用模板的另一个优点是,您可以创建和存储您希望在运行时应用的格式样式,如下所示:
oDoc.Bookmarks.Item("MyBookmark").Range.Style = "MyStyle"
- 或者 -
oWord.Selection.Style = "MyStyle"

参考

有关使用 Visual Basic .NET 来自动化 Microsoft Word 的其他信息,请单击下面的文章编号,以查看 Microsoft 知识库中相应的文章:
301656 (http://support.microsoft.com/kb/301656/EN-US/) HOWTO:Automate Microsoft Word to Perform a Mail Merge from Visual Basic .NET
有关详细信息,请访问下面的 Microsoft Developer Network (MSDN) 网站:
Microsoft Office Development with Visual Studio(使用 Visual Studio 进行 Microsoft Office 开发)
http://msdn2.microsoft.com/en-us/library/aa188489(office.10).aspx (http://msdn2.microsoft.com/en-us/library/aa188489(office.10).aspx)

Word in the Office(Office 中的 Word)
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnofftalk/html/office112000.asp (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnofftalk/html/office112000.asp)

One More Word
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnofftalk/html/office12072000.asp (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnofftalk/html/office12072000.asp)

这篇文章中的信息适用于:
Microsoft Visual Basic .NET 2003 标准版
Microsoft Visual .NET 2002 标准版
Microsoft Office Word 2003
Microsoft Word 2002 标准版

posted on 2007-03-13 14:55  王振鹏  阅读(351)  评论(0编辑  收藏  举报

导航