VB.Net Tutorial/Windows/Word

Материал из VB Эксперт
Версия от 15:56, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Create Word document and print

<source lang="vbnet">public class Test

  public Shared Sub Main
       Dim objWordApp As Word.Application
       objWordApp = New Word.Application
       Dim objDoc As New Word.Document
       "Show the Word application window if checked.
       objWordApp.Visible = IIf(chkShowWord.Checked, True, False)
       "Create a new Word document and add some text to it.
       objDoc = objWordApp.Documents.Add
       With objDoc
           .Range.InsertAfter("Printing with Word")
           .Paragraphs.Item(1).Range.Font.Bold = True
           .Paragraphs.Item(1).Range.Font.Size = 14
           .Range.InsertParagraphAfter()
           .Paragraphs.Item(2).Range.Font.Bold = False
           .Paragraphs.Item(2).Range.Font.Size = 12
           .Range.InsertAfter("This is the first line of the test printout")
           .Range.InsertParagraphAfter()
           .Range.InsertAfter("and this is the second line of the test printout")
           Try
               "Print the Word document.
               .PrintOut(True, True)
           Catch exc As Exception
               Console.WriteLine(exc.Message)
           End Try
       End With


       objWordApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
       objWordApp.Quit()
       objWordApp = Nothing
  End Sub

End class</source>

Edit Word document

<source lang="vbnet">public class Test

  public Shared Sub Main
       Dim objWordApp As Word.Application
       objWordApp = New Word.Application
       Dim objWordApp As Word.Application
       objWordApp = New Word.Application
       Dim objDoc As Word.Document
       "Show the Word application window if checked.
       objWordApp.Visible = IIf(chkShowWord.Checked, True, False)
       "Open an existing document.
       objWordApp.Documents.Open("C:\Temp\Sample.doc")
       objDoc = objWordApp.ActiveDocument
       "Find and replace some text.
       objDoc.Content.Find.Execute(FindText:="VB", _
           ReplaceWith:="Visual Basic Express", _
           Replace:=Word.WdReplace.wdReplaceAll)
       While objDoc.Content.Find.Execute(FindText:="  ", _
           Wrap:=Word.WdFindWrap.wdFindContinue)
           objDoc.Content.Find.Execute(FindText:="  ", ReplaceWith:=" ", _
               Replace:=Word.WdReplace.wdReplaceAll, _
               Wrap:=Word.WdFindWrap.wdFindContinue)
       End While
       "Save and close the document.
       objWordApp.Documents.Item(1).Save()
       Console.WriteLine("Replaced all instances of "VB" with "Visual Basic Express" " & _
           "and saved the document")


       objWordApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
       objWordApp.Quit()
       objWordApp = Nothing
       objWordApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
       objWordApp.Quit()
       objWordApp = Nothing
  End Sub

End class</source>

InsertAfter

<source lang="vbnet">public class Test

  public Shared Sub Main
       Dim objWordApp As Word.Application
       objWordApp = New Word.Application
       Dim objDoc As New Word.Document
       Dim objRange As Word.Range
       Dim strFileName As String
       "Show the Word application window if checked.
       objWordApp.Visible = IIf(chkShowWord.Checked, True, False)
       "Create a new Word document and add some text to it.
       objDoc = objWordApp.Documents.Add
       With objDoc.Range
           .InsertAfter("A ")
           .InsertParagraphAfter()
           .InsertAfter("A")
           .InsertParagraphAfter()
           .InsertAfter("A")
           .InsertParagraphAfter()
           .InsertParagraphAfter()
           .InsertAfter("A")
       End With
       objRange = objDoc.Paragraphs.Item(1).Range
       objRange.Font.Size = 14
       objRange.Font.Bold = True
       objRange.ParagraphFormat.Alignment = _
          Word.WdParagraphAlignment.wdAlignParagraphCenter
       objRange = objDoc.Paragraphs.Item(2).Range.Sentences.Item(2)
       objRange.Italic = True
       objRange = objDoc.Paragraphs.Item(3).Range.Words.Item(6)
       objRange.Font.Bold = True
       objRange = objDoc.Paragraphs.Item(5).Range.Words.Item(5)
       objRange.Font.Bold = True
       "Save the the document.
       SaveFileDialog1.Filter = "Documents|*.doc"
       SaveFileDialog1.ShowDialog()
       strFileName = SaveFileDialog1.FileName
       If strFileName <> "" Then
           Try
               objDoc.SaveAs(strFileName)
           Catch exc As Exception
               Console.WriteLine("Failed to save document." & vbCrLf & exc.Message)
           End Try
       End If
       "Display summary information.
       Console.WriteLine("The document contains " & objDoc.Paragraphs.Count & _
           " paragraphs, " & vbCrLf & objDoc.Words.Count & _
           " words, and " & objDoc.Characters.Count & " characters.")
       objWordApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
       objWordApp.Quit()
       objWordApp = Nothing
  End Sub

End class</source>

Type Text

<source lang="vbnet">public class Test

  public Shared Sub Main
       Dim objWordApp As Word.Application
       objWordApp = New Word.Application
       Dim objDoc As New Word.Document
       Dim strText As String
       Dim strFileName As String
       "Show the Word application window if checked.
       objWordApp.Visible = IIf(chkShowWord.Checked, True, False)
       "Create a new Word document and add some text to it.
       objDoc = objWordApp.Documents.Add
       strText = "Text Formatting:"
       With objWordApp.Selection
           .Font.Size = objWordApp.Selection.Font.Size + 2
           .Font.Bold = True
           .TypeText(strText)
           .Font.Size = objWordApp.Selection.Font.Size - 2
           .Font.Bold = False
           .TypeParagraph()
           .Font.Color = Word.WdColor.wdColorDarkRed
           .Font.Italic = False
           .TypeText("This sentence will appear in red. ")
           .TypeParagraph()
           .Font.Color = Word.WdColor.wdColorBlack
           .Font.Italic = True
           .Font.Size = objWordApp.Selection.Font.Size + 2
           .TypeText("Text color was reset to black, " & _
                     "but the font size was increased by two points.")
       End With
       "Save the the document.
       SaveFileDialog1.Filter = "Documents|*.doc"
       SaveFileDialog1.ShowDialog()
       strFileName = SaveFileDialog1.FileName
       If strFileName <> "" Then
           Try
               objDoc.SaveAs(strFileName)
           Catch exc As Exception
               Console.WriteLine("Failed to save document." & vbCrLf & exc.Message)
           End Try
       End If
       "Display summary information.
       Console.WriteLine("The document contains " & objDoc.Paragraphs.Count & " paragraphs, " & _
           vbCrLf & objDoc.Words.Count & " words, and " & _
           objDoc.Characters.Count & " characters.")


       objWordApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
       objWordApp.Quit()
       objWordApp = Nothing
  End Sub

End class</source>

Word Selection

<source lang="vbnet">public class Test

  public Shared Sub Main
       Dim objWord As New Word.Application
       objWord.Visible = True
       objWord.Documents.Add()
       objWord.Selection.TypeText("This is text from a VB 2005 application.")
       objWord = Nothing
  End Sub

End Class</source>

Word Spell Checker

<source lang="vbnet">Imports System.Windows.Forms public class WordSpellChecker

  public Shared Sub Main
       Application.Run(New Form1)
  End Sub

End class Public Class Form1

   Dim objWordApp As Word.Application
   Dim objCorrectionsCollection As Word.SpellingSuggestions
   Dim objSpellCollection As Word.ProofreadingErrors
   Private Sub OpenWord()
       objWordApp = New Word.Application
   End Sub
   Private Sub CloseWord()
       objWordApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
       objWordApp.Quit()
       objWordApp = Nothing
   End Sub
   Private Sub btnSpellCheckDoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSpellCheckDoc.Click
       Dim objRange As Word.Range
       Dim intWord As Integer
       Dim strNewWord As String
       Me.Text = "Starting Word ..."
       Call OpenWord()
       objWordApp.Documents.Add()
       Me.Text = "Checking words..."
       objRange = objWordApp.ActiveDocument.Range
       objRange.InsertAfter(TextBox1.Text)
       objSpellCollection = objRange.SpellingErrors
       If objSpellCollection.Count > 0 Then
           ListBox1.Items.Clear()
           ListBox2.Items.Clear()
           For intWord = 1 To objSpellCollection.Count
               strNewWord = objSpellCollection.Item(intWord).Text
               If ListBox1.FindStringExact(strNewWord) < 0 Then
                   ListBox1.Items.Add(strNewWord)
               End If
           Next
       End If
       Me.Text = "WordSpellChecker"
   End Sub
   Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
       Call CloseWord()
   End Sub
   Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
       Dim intWord As Integer
       objCorrectionsCollection = objWordApp.GetSpellingSuggestions(ListBox1.Text)
       ListBox2.Items.Clear()
       If objCorrectionsCollection.Count > 0 Then
           For intWord = 1 To objCorrectionsCollection.Count
               ListBox2.Items.Add(objCorrectionsCollection.Item(intWord).Name)
           Next
       Else
           ListBox2.Items.Add("No suggestions!")
       End If
   End Sub
   Private Sub btnReplaceWord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReplaceWord.Click
       If ListBox1.SelectedIndex >= 0 And ListBox2.SelectedIndex >= 0 Then
           TextBox1.Text = Replace(TextBox1.Text, _
               ListBox1.SelectedItem, ListBox2.SelectedItem)
           ListBox1.Items.Remove(ListBox1.SelectedIndex)
           ListBox2.Items.Clear()
       End If
   End Sub

End Class Partial Public Class Form1

   Inherits System.Windows.Forms.Form
   <System.Diagnostics.DebuggerNonUserCode()> _
   Public Sub New()
       MyBase.New()
       "This call is required by the Windows Form Designer.
       InitializeComponent()
   End Sub
   "Form overrides dispose to clean up the component list.
   <System.Diagnostics.DebuggerNonUserCode()> _
   Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
       If disposing AndAlso components IsNot Nothing Then
           components.Dispose()
       End If
       MyBase.Dispose(disposing)
   End Sub
   "Required by the Windows Form Designer
   Private components As System.ruponentModel.IContainer
   "NOTE: The following procedure is required by the Windows Form Designer
   "It can be modified using the Windows Form Designer.  
   "Do not modify it using the code editor.
   <System.Diagnostics.DebuggerStepThrough()> _
   Private Sub InitializeComponent()
       Me.TextBox1 = New System.Windows.Forms.TextBox
       Me.btnSpellCheckDoc = New System.Windows.Forms.Button
       Me.btnReplaceWord = New System.Windows.Forms.Button
       Me.ListBox1 = New System.Windows.Forms.ListBox
       Me.ListBox2 = New System.Windows.Forms.ListBox
       Me.Label1 = New System.Windows.Forms.Label
       Me.Label2 = New System.Windows.Forms.Label
       Me.SuspendLayout()
       "
       "TextBox1
       "
       Me.TextBox1.Location = New System.Drawing.Point(10, 9)
       Me.TextBox1.Multiline = True
       Me.TextBox1.Name = "TextBox1"
       Me.TextBox1.Size = New System.Drawing.Size(352, 192)
       Me.TextBox1.TabIndex = 0
       Me.TextBox1.Text = "This is some example text that contains misspelled words. For example, Visual Bas" & _
           "ci Espress."
       "
       "btnSpellCheckDoc
       "
       Me.btnSpellCheckDoc.Location = New System.Drawing.Point(369, 9)
       Me.btnSpellCheckDoc.Name = "btnSpellCheckDoc"
       Me.btnSpellCheckDoc.Size = New System.Drawing.Size(158, 23)
       Me.btnSpellCheckDoc.TabIndex = 3
       Me.btnSpellCheckDoc.Text = "SpellCheck Document"
       "
       "btnReplaceWord
       "
       Me.btnReplaceWord.Location = New System.Drawing.Point(369, 306)
       Me.btnReplaceWord.Name = "btnReplaceWord"
       Me.btnReplaceWord.Size = New System.Drawing.Size(158, 23)
       Me.btnReplaceWord.TabIndex = 4
       Me.btnReplaceWord.Text = "Replace Word"
       "
       "ListBox1
       "
       Me.ListBox1.FormattingEnabled = True
       Me.ListBox1.Location = New System.Drawing.Point(10, 232)
       Me.ListBox1.Margin = New System.Windows.Forms.Padding(3, 1, 3, 3)
       Me.ListBox1.Name = "ListBox1"
       Me.ListBox1.Size = New System.Drawing.Size(168, 95)
       Me.ListBox1.TabIndex = 1
       "
       "ListBox2
       "
       Me.ListBox2.FormattingEnabled = True
       Me.ListBox2.Location = New System.Drawing.Point(196, 232)
       Me.ListBox2.Margin = New System.Windows.Forms.Padding(3, 1, 3, 3)
       Me.ListBox2.Name = "ListBox2"
       Me.ListBox2.Size = New System.Drawing.Size(166, 95)
       Me.ListBox2.TabIndex = 2
       "
       "Label1
       "
       Me.Label1.AutoSize = True
       Me.Label1.Location = New System.Drawing.Point(10, 217)
       Me.Label1.Margin = New System.Windows.Forms.Padding(3, 3, 3, 0)
       Me.Label1.Name = "Label1"
       Me.Label1.Size = New System.Drawing.Size(94, 14)
       Me.Label1.TabIndex = 5
       Me.Label1.Text = "Misspelled words:"
       "
       "Label2
       "
       Me.Label2.AutoSize = True
       Me.Label2.Location = New System.Drawing.Point(196, 217)
       Me.Label2.Margin = New System.Windows.Forms.Padding(3, 3, 3, 0)
       Me.Label2.Name = "Label2"
       Me.Label2.Size = New System.Drawing.Size(94, 14)
       Me.Label2.TabIndex = 6
       Me.Label2.Text = "Alternative words:"
       "
       "Form1
       "
       Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
       Me.ClientSize = New System.Drawing.Size(539, 342)
       Me.Controls.Add(Me.Label2)
       Me.Controls.Add(Me.Label1)
       Me.Controls.Add(Me.ListBox2)
       Me.Controls.Add(Me.ListBox1)
       Me.Controls.Add(Me.btnReplaceWord)
       Me.Controls.Add(Me.btnSpellCheckDoc)
       Me.Controls.Add(Me.TextBox1)
       Me.Name = "Form1"
       Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
       Me.Text = "WordSpellChecker"
       Me.ResumeLayout(False)
       Me.PerformLayout()
   End Sub
   Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
   Friend WithEvents btnSpellCheckDoc As System.Windows.Forms.Button
   Friend WithEvents btnReplaceWord As System.Windows.Forms.Button
   Friend WithEvents ListBox1 As System.Windows.Forms.ListBox
   Friend WithEvents ListBox2 As System.Windows.Forms.ListBox
   Friend WithEvents Label1 As System.Windows.Forms.Label
   Friend WithEvents Label2 As System.Windows.Forms.Label

End Class</source>