下面是我的Vb代码,它获取了excel文件的行数。但是,如果行计数大于10k行,我想抛出异常并给出错误消息。我怎么能这样做?我已经完成了关于获取行数但不确定如何抛出异常的研究。以下是ASP.Net Windows窗体应用程序。
Dim xls As New Excel.Application
Dim sheet As Excel.Worksheet
Dim filePath As String = Path.Combine(GlobalVariable.savedPath, GlobalVariable.excelFileName)
xls.Workbooks.Open(filePath)
sheet = xls.ActiveWorkbook.Sheets(1)
Dim maxSize As Integer = 2
Dim row As Integer = 1
Do Until sheet.Cells(row, 1).value Is Nothing
row += 1
Loop
MsgBox("last Row is " & row - 1)
xls.Workbooks.Close()
xls.Quit()
releaseObject(sheet)
releaseObject(xls)
答案 0 :(得分:2)
您已经在计算行数,因此您可以修改循环以仅在行小于10,000时继续。
Dim row As Integer = 1
Do
row += 1
Loop while sheet.Cells(row, 1).value IsNot Nothing AndAlso row <= 10000
这将循环,递增行直到没有更多行,或者如果你达到10,000。然后,您可以检查行是否为10,000,以决定是否要显示错误消息。
If row >= 10000 then
MsgBox("Over 10000 rows")
'If you want to throw an actual exception you can do:
Throw new Exception("Over 10000 rows")
Else
MsgBox("last Row is " & row - 1)
End If
我不知道如果行达到10,000,我是否会建议抛出异常来处理。相反,我会这样做:
Private Sub BtnUpload_OnClick(sender As Object, e As EventArgs) Handles BtnUplaod.Click
REM Save SpreadSheet
Dim filePath As String = Path.Combine(GlobalVariable.savedPath, GlobalVariable.excelFileName)
myfileUploader.saveAs(filePath)
REM Open SpreadSheet
Dim xls As New Excel.Application
Dim sheet As Excel.Worksheet
xls.Workbooks.Open(filePath)
sheet = xls.ActiveWorkbook.Sheets(1)
Dim maxSize As Integer = 2
REM Loop through spreadsheet and count rows
Dim row As Integer = 1
Do
row += 1
Loop While sheet.Cells(row, 1).value IsNot Nothing AndAlso row <= 10000 'Exit loop when end of SpreadSheet is reached or if rows exceeds 10,000
REM Release Resources
xls.Workbooks.Close()
xls.Quit()
releaseObject(sheet)
releaseObject(xls)
REM Decide whether to accept upload, or reject and show error
If row >= 10000 Then 'If row > 10000 delete file and show error
REM Delete the file
File.Delete(filePath)
REM Show some sort of error to user - Its up to you how you want to do so. That is a seperate question
MsgBox("Your Error")
REM Else SpreadSheet is valid
Else
'Your Code code doing what you want with spreadsheet goes here
MsgBox("last Row is " & row - 1)
End If
End Sub
当用户在WebPage上单击名为BtnUpload的按钮时,将运行此代码。你可以把它放在任何你喜欢的地方。
我认为这就是你想要的。这是对的吗?