vb.net将文本文件导入由空格分隔的excel

时间:2016-12-23 17:10:27

标签: vb.net import stream text-files readlines

想知道是否有人有一个示例vb代码将文本文件导入到由空格分隔的excel中 - 无论空格数多少。在文本文件中有例如100k行,并且在每行中,每个单词可以由一个,两个或三个等空格分隔。

导入到excel的结果是文本文件中的每一行都在每一行中,每行由空格分隔的每个单词都在该行的每一列中。

我尝试通过读取文本文件中的每一行然后解析每一行的每个单词来完成此操作,并将它们放入变量中,然后将其写入excel。我认为这种方式需要更长的时间,而我正处于解析每一行的过程中。但我认为如果可以这样做,将文本文件导入由空格分隔的excel会更快。我使用vb而不是vba的原因是因为vb可以创建一个可由调度程序运行的可执行文件。感谢

Dim reader As New System.IO.StreamReader("C:\test.txt")
Dim allLines As List(Of String) = New List(Of String)
Dim stringreader As String
Dim a As String
    stringreader = filereader.ReadLine()

    Do While Not reader.EndOfStream
      allLines.Add(reader.ReadLine())
      stringreader = reader.ReadLine()
      MsgBox("The first line of the file is                " & stringreader)
    Loop

1 个答案:

答案 0 :(得分:2)

在此示例中,首先打开StreamReaderExcel。然后添加新的Workbook和新的Worksheet。最后,逐行读取文本文件。每行在空格上分割并写入Excel Worksheet。处理完文本文件后,Stream将关闭,结果Excel将保持打开状态。 HTH

  

为您的Excel版本安装Office主互操作程序集。

     

(示例使用对Ecel 2007 PIA的引用:C:\ Windows \ assembly \ GAC \ Microsoft.Office.Interop.Excel \ 12.0.0.0__71e9bce111e9429c \ Microsoft.Office.Interop.Excel.dll)

Imports System.IO
Imports ExcelInterop = Microsoft.Office.Interop.Excel

Module Module2
   Sub Main()
        Dim reader As StreamReader = New StreamReader("C:\test.txt")
        Dim targetWorksheet As ExcelInterop.Worksheet = GetTargetWorksheet("c:\test.xls")
        if targetWorksheet Is Nothing Then
            Exit Sub
        End If
        Try
            Dim line As String
            Dim lineIndex As Long = 1
            Do While reader.Peek() >= 0
                line = reader.ReadLine()
                WriteToExcel(line, targetWorksheet, lineIndex)
                lineIndex += 1 
            Loop
        Catch ex As Exception
            Debug.WriteLine("The file could not be read:")
            Debug.WriteLine(ex.Message)
        finally
            If Not reader Is Nothing Then
                reader.Close()
            End If
        End Try
    End Sub

   Private Sub WriteToExcel(line As String, targetWorksheet As ExcelInterop.Worksheet, lineIndex As Long)
        Dim column As Integer = 1
        For Each part As String In line.Split(" ")
            targetWorksheet.Cells(lineIndex, column).Value =part
            column += 1
       Next
   End Sub

    Private Function GetTargetWorksheet(targetPath As String) As ExcelInterop.Worksheet
        Try
            Dim excelApplication = New ExcelInterop.Application
            excelApplication.Visible = True
            Dim excelWorkbook As ExcelInterop.Workbook
            excelWorkbook = excelApplication.Workbooks.Add()
            excelWorkbook.SaveAs(targetPath)
            Dim excelWorksheet As ExcelInterop.Worksheet = excelWorkbook.Worksheets.Add()
            excelWorksheet.Name = "Import"
            return excelWorksheet
        Catch ex As Exception
            Debug.WriteLine("The excel worksheet could not be created:")
            Debug.WriteLine(ex.Message)
        End Try
        Return Nothing
    End Function
End Module

编辑:

可以使用QueryTables Excel来导入文本数据。有一些设置需要考虑,例如TextFileColumnDataTypes。在此示例中,所有列都设置为xlColumnDataType.xlTextFormat

Sub Main()
    Dim targetWorksheet As Worksheet = GetTargetWorksheet("c:\test.xls")
    if targetWorksheet Is Nothing Then
        Debug.WriteLine("Target sheet is Nothing.")
        Exit Sub
    End If

    Try
        Dim qt As QueryTable
        qt = targetWorksheet.QueryTables.Add( _
        Connection:="TEXT;C:\test.txt", _
        Destination:=targetWorksheet.Range("$A$1"))

        With qt
            .Name = "Import"
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = XlCellInsertionMode.xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = 1252
            .TextFileStartRow = 1
            .TextFileParseType = XlTextParsingType.xlDelimited
            .TextFileTextQualifier = XlTextQualifier.xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = True
            .TextFileTabDelimiter = False
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = False
            .TextFileSpaceDelimiter = True
            .TextFileColumnDataTypes = GetColumnDataTypes(targetWorksheet.Columns.Count)
            .TextFileTrailingMinusNumbers = True
            .Refresh(BackgroundQuery := False)
        End With

    Catch ex As Exception
        Debug.WriteLine("The file could not be read:")
        Debug.WriteLine(ex.Message)
    End Try
End Sub

Private Function GetColumnDataTypes(queryTableColumnsCount As long) As Object
    Dim textDataTypes As xlColumnDataType()
    textDataTypes = Enumerable.Repeat(xlColumnDataType.xlTextFormat, queryTableColumnsCount).ToArray()
    Return textDataTypes          
End Function