简体   繁体   中英

VB.Net Working with and Manipulating an Excel Spreadsheet

I want to iterate through a row in my dataset. If the first cell of the row is of the pattern 1234-Name , then I want to strip the number (1234) from that and save it as a variable. Basically, the first cell is the employee and their number, like 1234-Bob McDonald . If it isn't of that form then I want to ignore it and move to the next row.

Then I want to go cell by cell in the same row, and whatever is in the cell, save it to a different variable (column 2 is location, column 3 is number of hours worked, etc.)

Here is the code I have so far:

Public Function ReadXLFile(ByVal FileName As String) As DataSet
    Dim MyConnection As System.Data.OleDb.OleDbConnection
    Dim Ds As System.Data.DataSet
    Dim MyAdapter As System.Data.OleDb.OleDbDataAdapter
    MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FileName & "Extended Properties=Excel 16.0;")
    MyAdapter = New System.Data.OleDb.OleDbDataAdapter("Select * from [Sheet1$]", MyConnection)
    Ds = New System.Data.DataSet
    MyAdapter.Fill(Ds)
    Return Ds
End Function

How about this?

Public Sub GetData(ByVal FileName As String)
    Dim strEmployeeNumber As String
    Dim strEmployeeName As String
    Dim strLocation As String
    Dim intHours As Integer
    Dim myDataSet As DataSet = ReadXLFile(FileName)
    Dim myFirstCell As String
    Dim mMatch As Match
    Dim r As Regex = New Regex("^[0-9]+-[A-Za-z]+")
    Dim arrFirstCell() As String
    For Each myDr As DataRow In myDataSet.Tables(0).Rows
        myFirstCell = myDr.Item(myDataSet.Tables(0).Columns(0))
        mMatch = r.Match(myFirstCell)
        If mMatch.Success Then
            arrFirstCell = Split(mMatch.Value, "-")
            strEmployeeNumber = arrFirstCell(0)
            strEmployeeName = arrFirstCell(1)
            strLocation = myDr.Item(myDataSet.Tables(0).Columns(1))
            intHours = CInt(myDr.Item(myDataSet.Tables(0).Columns(2)))
            Console.WriteLine("Number: {0}  Name: {1}  Location: {2}  Hours: {3}", strEmployeeNumber, strEmployeeName, strLocation, intHours)
        End If
    Next
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM