我有一个大约80000行的Excel电子表格,用户将自动过滤器应用到工作表并将其加载到VB.NET应用程序中。 有没有办法可以使用ADO.NET只读取过滤的行?我不想使用Excel Interop,因为并非所有用户都安装了MS Office。该应用程序旨在只读XLSX文件。
感谢您的期待
答案 0 :(得分:0)
使用ODBC或OLEDB dataProvider使用sql查询。 例如:
Dim connection = New OdbcConnection("Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=C:\MyExcel.xlsx;")
Dim com As New OdbcCommand("SELECT * FROM [SheetName$] WHERE ID > 5", connection)
connection.Open()
Dim reader = com.ExecuteReader()
While reader.Read()
'get data
Console.WriteLine("{0} {1}", reader(0), reader(1))
End While
connection.Close()
另一种方式: linq-to-excel。我还没用过它。
答案 1 :(得分:0)
for filter根据AutoFilter,您需要从File中读取AutoFilter,并生成sql表达式。 我给你写了一个结构代码,用OpenXml库读取AutoFilter:
Dim SheetName = "SheetName"
Dim fileFullName As String = "C:\MyExcel.xlsx"
Dim SqlFilterExpression As String
Using xslDoc As SpreadsheetDocument = SpreadsheetDocument.Open(fileFullName, False)
Dim theSheet As Sheet = xslDoc.WorkbookPart.Workbook.Sheets.FirstOrDefault(Function(SheetEl) CType(SheetEl, Sheet).Name = SheetName)
Dim WorkSheetPart As WorksheetPart = xslDoc.WorkbookPart.GetPartById(theSheet.Id)
Dim Filter = WorkSheetPart.Worksheet.Elements(Of AutoFilter).First
If Not IsNothing(Filter) Then
For Each FilterPerColumn In Filter.Elements(Of FilterColumn)()
Dim CustomFilters = FilterPerColumn.Elements(Of CustomFilters).FirstOrDefault
If Not IsNothing(CustomFilters) Then
Dim filters = CustomFilters.Elements(Of CustomFilter)()
'check if filter contient tow condition
If filters.Count = 1 Then
Select Case CType(filters(0).Operator, FilterOperatorValues)
Case FilterOperatorValues.LessThan
'...Ect.
End Select
Else
'check if condition joined by or/and
If CustomFilters.And Then
'and joined
Else
'or joined
End If
End If
End If
Next
End If
End Using
因为毕竟XML是一个串行访问文件,所以通过OpenXml读取所有文件很可能会花费相同的时间。