1

我需要将读取的数据从 excel 循环到 vb.net,当我到达最后一行/列“!@#$%^&*()”时,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 = "'!@#$%^&*()_+" 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
4

2 回答 2

6

您似乎想多了,您可以通过访问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)
于 2012-12-09T17:32:11.353 回答
2

您可以使用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 "*'!@#$%^&*") 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

请查看以下参考资料,以更好地了解您的选择。

于 2012-12-03T02:41:55.187 回答