循环遍历Excel文件中的每一行

时间:2015-10-23 07:52:03

标签: asp.net vb.net excel

我有一个包含许多列的Excel文件,但我只需要列NAMECostTime。我需要逐行循环我的Excel,但是对于名称/成本/时间列,要将值保存在变量中。

 If FileUpload1.HasFile = False Then

        Exit Sub
    Else
        Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
        Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
        'Dim FolderPath As String = ConfigurationManager.AppSettings("Upload")

 Protected Sub ButtonVerify_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButtonVerify.Click


    If FileUpload1.HasFile = False Then

        Exit Sub
    Else
        Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
        Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
        'Dim FolderPath As String = ConfigurationManager.AppSettings("Upload")

        Dim FilePath As String = Server.MapPath("~") & "\Upload\" & FileName
        FileUpload1.SaveAs(FilePath)

        Dim existingFile = New FileInfo(FilePath)
        Dim pack As ExcelPackage = New ExcelPackage(existingFile)
        Dim workBook As ExcelWorkbook = pack.Workbook


        If workBook.Worksheets.Count > 0 Then
            Dim currentWorksheet As ExcelWorksheet = workBook.Worksheets.First()


            Dim Requester As String = currentWorksheet.Cells(30, 2).Value

        End If

    End If

    LBL_Error.Text = Nothing

    LBL_Status.Text = "Your file have been upload in your form. Please complete your Sample Order!"
End Sub

其中If workBook.Worksheets.Count > 0然后我需要循环来自单元格的每个值,最后计算一个框中所有时间的平均值。

1 个答案:

答案 0 :(得分:0)

要仅对某些列循环,您可以这样做:

Dim WB As Excel.Workbook
Dim WS As Excel.Worksheet
Dim DateRng As Excel.Range
Dim AccountsRng As Excel.Range
Dim i As Long

WB = xlApp.Workbooks.Add
WS = WB.Worksheets("Sheet1")

DateRng = WS.Columns(2)     ' Change the '2' as necessary.

With DateRng
    For i = 1 To .Count
      'Do your stuff
    Next i
End With

通过这种方式,您可以按照以下说明选择要使用的列: https://msdn.microsoft.com/en-us/library/office/ff197266.aspx

Excel.Worksheet.Columns(1)将是您的A列