导入CSV,其中标题不是顶行

时间:2014-05-29 15:03:02

标签: .net excel csv

我有一个客户端,我直接从CSV导入数据,但是他们的一些Excel工作表首先说出公司徽标和通用文本。这些文件也会发送给他们的第三方,因此我们希望保持格式不变。

我能够匹配行标题并将CSV导入Excel,其中名称位于第一行,我怎样才能看到'说第3行?

我删除了大部分错误处理,因为它很长!

Protected Sub btnExcelToSQL_Click(sender As Object, e As System.EventArgs) Handles btnExcelToSQL.Click


    lblText.ForeColor = System.Drawing.Color.Green
    lblText.Text = " "

    '#############  //'Check valid file type for photo

    If FileUpload1.HasFile Then

        Dim extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
        If extension.ToLower() = ".xlsx" Or extension.ToLower() = ".xls" Then
            Dim vExtention As String
            vExtention = extension.ToLower
            'is okay
        Else

            'nothing to check
            lblText.Visible = True
            lblText.ForeColor = System.Drawing.Color.Red
            lblText.Text = "Choose a file in that is one of the following types to upload. (xlsx - Excel File) "
            Exit Sub
        End If
    End If

    '#############  \\'Check valid file type for the file

    Dim vFileName As String = FileUpload1.PostedFile.FileName
    Dim uploadFolder As String = "C:\sites\Examples\CSVUpload\UploadedExcel\" + DateTime.Now.ToString("dd-m-yyyy-HH-mm-ss") + "_" + vFileName

    'We add a date to stop any files having the same name

    FileUpload1.SaveAs(uploadFolder)

    Dim excelConnectionString As String = (Convert.ToString("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=") & uploadFolder) + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';"

    '#### Upload, Rename and save file 
    '#### Open Excel to Parse here
    Dim ds As New DataSet
    Dim oleda As New OleDbDataAdapter()
    Dim cmdExcel As New OleDbCommand()
    '#### End - Open Excel to Parse here


    Dim excelConnection As New OleDbConnection(excelConnectionString)
    With cmdExcel
        .CommandText = "Select  [Unique Property Reference Number] from [Page 1$]" 'Names we want to select and the name of the sheet
        .CommandType = CommandType.Text
        .Connection = excelConnection
    End With
    excelConnection.Open()

    oleda = New OleDbDataAdapter(cmdExcel)
    oleda.Fill(ds, "dataExcel")

    If ds.Tables("dataExcel").Rows.Count > 0 Then

        '#### Stored procedure details
        Dim connection As SqlConnection
        Dim commandSQL As New SqlCommand

        Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("SQLLocal").ToString()
        '########### End - Stored procedure details
        'Set date once 
        Dim vDate As Date
        vDate = DateTime.Now.AddDays(0)

        connection = New SqlConnection(ConnectionString)
        connection.Open()

        'Dims for error handling and checking for invalid characters


        For j As Integer = 0 To ds.Tables("dataExcel").Rows.Count - 1 ' counted rows so loop through, ignores first row with names in 

            If (IsDBNull(ds.Tables("dataExcel").Rows(j)("Unique Property Reference Number"))) Then
                'skip
            Else

                'Bring the data across, the rows(i)("xxx") must match a name on the Excel sheet but DOES NOT have to be in order
                With commandSQL
                    .Connection = connection
                    .CommandText = "spAddCSVDataLineAsbestos"  'Stored procedure here
                    .CommandType = CommandType.StoredProcedure

                    .Parameters.AddWithValue("UPRN", If(IsDBNull(ds.Tables("dataExcel").Rows(j)("Unique Property Reference Number")), "", Trim(ds.Tables("dataExcel").Rows(j)("Unique Property Reference Number"))))
                    .Parameters.AddWithValue("DateTimeAdded", vDate) ' Date set at start

                    .ExecuteNonQuery() 'Execute the query
                    .Dispose() 'dispose of the commandSQL
                    .Parameters.Clear() 'dispose of the Parameters, otherwise on the second loop we would still have the first Parameters live
                End With
            End If
        Next



        connection.Close() ' Close connection

        lblText.ForeColor = System.Drawing.Color.Blue
        lblText.Text = "File Uploaded " & ds.Tables("dataExcel").Rows.Count & " Rows Successfully"



    Else
        lblText.ForeColor = System.Drawing.Color.Red
        lblText.Text = "File appears to be empty"

    End If



End Sub

1 个答案:

答案 0 :(得分:1)

Microsoft Jet OLE DB 4.0提供程序允许您使用具有特定地址的范围。在工作表名称后面使用美元符号并连接表格范围。例如:[Sheet1 $ A1:B10] 。在VB.NET中做这样的事情:

  Private m_sConn1 As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
           "Data Source=C:\ExcelData1.xls;" & _
           "Extended Properties=""Excel 8.0;HDR=YES"""
  Dim conn1 As New System.Data.OleDb.OleDbConnection(m_sConn1)
  conn1.Open()
  Dim cmd1 As New System.Data.OleDb.OleDbCommand("Select * From [EmployeeData$A1:E100]", conn1)
  Dim rdr As OleDbDataReader = cmd1.ExecuteReader

  Debug.WriteLine(vbCrLf & "EmployeeData:" & vbCrLf & "=============")
  Do While rdr.Read()
     Debug.WriteLine(System.String.Format("{0,-10}{1, -15}{2}", _
        rdr.GetString(0), rdr.GetString(1), _
        rdr.GetDateTime(2).ToString("d")))
  Loop
  rdr.Close()
  conn1.Close()

检查一下: How To Use ADO.NET to Retrieve and Modify Records in an Excel Workbook With Visual Basic .NET