0

我有一个大约 80000 行的 Excel 电子表格,用户将自动过滤器应用于工作表并将其加载到 VB.NET 应用程序中。有没有办法我可以使用 ADO.NET 只读取过滤的行?我不想使用 Excel Interop,因为并非所有用户都安装了 MS Office。该应用程序旨在只读 XLSX 文件。

感谢期待

4

2 回答 2

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。我还没有使用它。

于 2013-10-01T16:48:26.557 回答
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 读取所有文件很可能会花费相同的时间。

于 2013-10-02T10:03:49.883 回答