简体   繁体   中英

read excel file in VB.NET with autofilter

I have an Excel spreadsheet with about 80000 rows, The users apply autofilter to the sheet and load it in the VB.NET application. Is there a way I can read only filtered rows using ADO.NET ?. I do not want to use Excel Interop because not all users have MS Office installed. The Application is designed to Read only XLSX files.

Thanks in anticipation

with ODBC or OLEDB dataProvider's with sql query. example:

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()

Another way: linq-to-excel . I have not used it yet.

for filter According the AutoFilter, you need read the AutoFilter from the File, and generate sql expression. I write you a structure code to read AutoFilter using OpenXml library:

 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

Because after all XML is a serial-access file, its very possible that reading all file by OpenXml will take the same time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM