章鱼哥出品—VB.NET Office操作之Word(一)
程序员文章站
2022-06-02 14:53:13
在这里给出了一个Word操作的类,该类具备了对word 文档操作的基本功能。在下一篇文章中我将给出这个类实现的实例,读者可以借鉴下
程序引用的是Microsoft Word 14....
在这里给出了一个Word操作的类,该类具备了对word 文档操作的基本功能。在下一篇文章中我将给出这个类实现的实例,读者可以借鉴下
程序引用的是Microsoft Word 14.0 Object Library 使用word 2007 +VS2010
'********************************************************************* '作者:章鱼哥,QQ:3107073263 群:309816713 '如有疑问或好的建议请联系我,大家一起进步 '********************************************************************* Imports Microsoft.Office.Interop Public Class Class_Word1 Public ZWordApplic As Word.Application Private ZDocument As Word.Document Public Sub New() '生成类实例 ZWordApplic = New Word.Application ZWordApplic.Visible = True End Sub '新建一个Word文档 Public Sub NewDocument() ZDocument = ZWordApplic.Documents.Add() '新建一个文档 End Sub '使用模板新建一个文档 Public Sub ModulNewDocument(ByVal FileAddress As String) ZDocument = ZWordApplic.Documents.Add(FileAddress) End Sub '打开一个文档 Public Sub OpenWordDocument(ByVal FileAddress As String, ByVal IsReadOnly As Boolean) Try ZDocument = ZWordApplic.Documents.Open(FileAddress, Nothing, IsReadOnly) Catch ex As Exception MsgBox("您输入的地址不正确") End Try End Sub '关闭一个文档 Public Sub CloseWordDocument() ZWordApplic.Quit() System.Runtime.InteropServices.Marshal.ReleaseComObject(ZWordApplic) ZWordApplic = Nothing End Sub '关闭所有打开的文档 Public Sub CloseAllDocuments() ' ZWordApplic.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges) ZWordApplic.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges) End Sub '保存文档 Public Sub Save() Try ZDocument.Save() MsgBox("保存成功") Catch ex As Exception MsgBox(ex.Message) End Try End Sub '另存为 Public Sub SaveAs(ByVal FileAdress As String) Try ZDocument.SaveAs2(FileAdress) MsgBox("另存为成功!") Catch ex As Exception MsgBox(ex.Message) End Try End Sub '插入文字 Public Sub InsertText(ByVal text As String) ZWordApplic.Selection.TypeText(text) End Sub '插入表格 Public Sub InsertTabel(ByVal Tabel As DataTable) Dim ZTabel As Word.Table ZTabel = ZDocument.Tables.Add(ZWordApplic.Selection.Range, Tabel.Rows.Count + 1, Tabel.Columns.Count) '添加表头 For i = 1 To Tabel.Columns.Count ZTabel.Rows(1).Cells(i).Range.InsertAfter(Tabel.Columns(i - 1).ColumnName) Next '添加表格数据 For i = 2 To Tabel.Rows.Count + 1 For j = 1 To Tabel.Columns.Count ZTabel.Rows(i).Cells(j).Range.InsertAfter(Tabel.Rows(i - 2).Item(j - 1).ToString) Next Next ZTabel.AllowAutoFit = True ZTabel.ApplyStyleFirstColumn = True ZTabel.ApplyStyleHeadingRows = True End Sub '插入图片 Public Sub InsertPic(ByVal PicAddress As String) Try ZWordApplic.Selection.InlineShapes.AddPicture(PicAddress, False, True) Catch ex As Exception MsgBox("图片地址不正确 ") End Try End Sub '读取文字 Public Sub ReadText() ZWordApplic.Selection.WholeStory() ZWordApplic.Selection.Copy() End Sub End Class