1 ‘Imports System.Collections.Generic 2 ‘Imports System.Text 3 ‘Imports System.IO 4 ‘Imports office = Microsoft.Office.Core 5 ‘Imports word = Microsoft.Office.Interop.Word 6 Module Module1 7 8 Sub Main(ByVal args As String()) ‘这里的参数args是字符串数组,传递的是\bin\Debug\中的文本文件,可以传递多个文件 9 Dim theApplication As New Microsoft.Office.Interop.Word.Application ‘添加引用COM的“Microsoft Word 12.0 Object Library” 10 theApplication.Visible = True 11 Dim theDocument As Microsoft.Office.Interop.Word.Document 12 theDocument = theApplication.Documents.Add() 13 Dim reader As System.IO.TextReader ‘添加引用COM的“Microsoft Visual Basic for Applications Extensibility 5.3” 14 reader = New System.IO.StreamReader("woshi.txt") ‘原语句是reader = New System.IO.StreamReader(args(0)) 15 ‘C:\Users\user\Documents\Visual Studio 2008\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\woshi.txt 16 17 Dim separators(1) As String 18 separators(0) = "||" 19 Dim rowCount As Integer = 0 20 Dim columnCount As Integer = 0 21 22 Dim rowList As New System.Collections.Generic.List(Of String) 23 Dim row As String = reader.ReadLine() 24 25 While row IsNot Nothing 26 rowCount += 1 27 rowList.Add(row) 28 29 If rowCount = 1 Then 30 Dim splitHeaderRow As String() = row.Split(separators, StringSplitOptions.None) 31 32 columnCount = splitHeaderRow.Length - 2 33 End If 34 35 row = reader.ReadLine() 36 End While 37 38 Dim range As Microsoft.Office.Interop.Word.Range = theDocument.Range() 39 Dim table As Microsoft.Office.Interop.Word.Table = range.Tables.Add(range, rowCount, columnCount) 40 41 Dim columnindex As Integer = 1 42 Dim rowindex As Integer = 1 43 44 For Each r As String In rowList 45 Dim splitrow As String() = r.Split(separators, StringSplitOptions.None) 46 47 For columnindex = 1 To columnCount 48 Dim cell As Microsoft.Office.Interop.Word.Cell = table.Cell(rowindex, columnindex) 49 cell.Range.Text = splitrow(columnindex) 50 Next 51 rowindex += 1 52 Next 53 54 table.Rows(1).Range.Bold = 1 55 table.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitContent) 56 57 System.Console.WriteLine("Table complete.") 58 System.Console.ReadLine() 59 60 theApplication.Quit(False) 61 62 End Sub 63 64 End Module
时间: 2024-10-13 23:27:23