2012-12-03 171 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