概述
1、定义excel操作变量
|
dim objexcelfile as excel.application
dim objworkbook as excel.workbook
dim objimportsheet as excel.worksheet
|
2、打开excel进程,并打开目标excel文件
|
set objexcelfile = new excel.application
objexcelfile.displayalerts = false
set objworkbook = objexcelfile.workbooks.open(strfilename)
set objimportsheet = objworkbook.sheets(1)
|
3、获取excel有效区域的行和列数
|
intlastcolnum = objimportsheet.usedrange.columns.count
intlastrownum = objimportsheet.usedrange.rows.count
|
4、逐行读取excel中数据
|
由于前两行为header部分,所以需要从第三行读取
如果第1到第10个单元格的值均为空或空格,则视为空行
for intcounti = 3 to intlastrownum
check if empty data row
blnnullrow = true
for inti = 1 to 10
if trim$(objimportsheet.cells(intcounti, inti).value) <> "" then
blnnullrow = false
end if
next inti
若不是空行,则进行读取动作,否则继续向后遍历excel中的行
if blnnullrow = false then
获取单元格中的数据,做有效性check,并将合法数据创建为实体存入对象数组中
objimportsheet.cells(intcounti, 1).value
……
end if
next intcounti
|
5、退出excel进程,并关闭excel相关操作对象
|
objexcelfile.quit
set objworkbook = nothing
set objimportsheet = nothing
set objexcelfile = nothing |
2
Public Shared Function PFn_ExcelToDataTable(FileName As String) As DataTable
Dim dtRetrunTable As New DataTable
Dim strConn As String = ("Provider=Microsoft.Ace.OleDb.12.0;" & "data source=") + FileName & ";Extended Properties='Excel 12.0; HDR=YES; IMEX=1'"
Dim conn As New OleDb.OleDbConnection(strConn)
conn.Open()
Dim myDataSet As DataSet = New DataSet
Dim strExcel = "SELECT * FROM [sheet1$]"
Using da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(strExcel, conn)
Try
da.Fill(myDataSet)
dtRetrunTable = myDataSet.Tables(0)
Catch ex As Exception
Finally
If conn.State = ConnectionState.Open Then
conn.Close()
conn = Nothing
End If
da.Dispose()
End Try
End Using
Return dtRetrunTable
End Function
最后
以上就是潇洒冰淇淋为你收集整理的vb.net 读取Excel的全部内容,希望文章能够帮你解决vb.net 读取Excel所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复