2012-12-03 122 views
1

我需要将读取的数据从excel循环到vb.net,当我到达最后一行/列“!@#$%^ & *()”时,excel数据将停止读取。我怎样才能做到这一点?循环读取excel数据

Imports Excel = Microsoft.Office.Interop.Excel 
Public Class Form1 
    Dim xlApp As Excel.Application 
    Dim xlWorkBook As Excel.Workbook 
    Dim xlWorkSheet As Excel.Worksheet 
    Dim xRange As Excel.Range 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
    End Sub 
    Private Sub cmdGenerate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGenerate.Click 
     'Dim row As String 
     Dim empty_cell_ctr As Integer = 0 '5 
     Dim end_of_xlsheet As Boolean = False 
     Dim sRow As Integer 'start row 
     Dim col_end As Integer 'col W 
     ' 
     'loading excel(open and read) 
     xlApp = New Excel.ApplicationClass 
     xlWorkBook = xlApp.Workbooks.Open("c:\sample.xls") 
     xlWorkSheet = xlWorkBook.Worksheets("Timesheet") 
     xlApp.Visible = True 

     While Not end_of_xlsheet 

      If sRow = "'[email protected]#$%^&*()_+" Then 
       xRange = xRange.Cells(sRow, col_end) 
       end_of_xlsheet = False 'end of sheet 
       Continue While 
      End If 

      sRow += 1 

     End While 

     MessageBox.Show(sRow) 
    End Sub 
End Class 
+0

重新读你的问题几次,现在我怀疑你真的需要什么...... :(你想停止时,它击中最后一排?那些角色在那里做什么? – bonCodigo

+0

Janine请接受答案并帮助更新系统,如果这回答你的问题:-) – bonCodigo

回答

1

您可以使用LIKE操作:)

'Not sure why you are trying to check Row number for set of characters... 

Excel.Range range = sheet.UsedRange; 
Int rows_count = range.Rows.Count; 

For (int sRow = 1; sRow <= rows_count; sRow++)    
    If (sheet.Cells[sRow, col_end].value Like "*'[email protected]#$%^&*") Then 
     '-- input the data to where ever you want. It is best to store it into an array first.. 
     xRange = sheet.Cells[i, col_end].value; 
     Break; 
    Else 
     sRow++;   
    End If 

请看看下面的参考为了更好地理解你的选择。

4

你似乎得太多这一点,你可以通过访问UsedRange属性来获取所有的电子表格中的数据,然后加载此通过访问此对象的Value2属性,将其转换为二维数组变量,如下所示:

Dim application = New Excel.Application() 
Dim workbook As Excel.Workbook = application.Workbooks.Open("C:\aaa\bbb.xlsx") 
Dim worksheet As Excel.Worksheet = workbook.Sheets(1) 

Dim usedRange = worksheet.UsedRange 
Dim usedRangeAs2DArray As Object(,) = usedRange.Value2 

workbook.Save() 
workbook.Close() 
application.Quit() 

Marshal.ReleaseComObject(application) 
+1

优秀,简单和明确的回应。可以将事件标记为答案。但我只需要添加一件事:Excel是基于1的索引,而不是任何其他的0基础索引Enumarable对象(以及这种情况下的数组类型)。记住'usedRangeAs2DArray'时记住这一点。这意味着XLusedRangeAs2DArray中的第一个可存取对象是XLusedRangeAs2DArray(1,1)。 – Minus

+0

非常真实,谢谢你的好话=) – JMK