2016-04-07 12 views
0

Şu anda 1500 satır ve 9 sütun içeren bir excel dosyası var. Winformum her yüklendiğinde, excel dosyasındaki kayıtların bir datagridview'a yüklenmesini istiyorum. Kayıtları datagridview'e aktarmak için Microsoft Office Interop kullanıyordum ama çok yavaş.Nasıl datagridview excel almak için excel ithal etmek daha hızlı kullanarak.

Benim sorum şu ki, başka hangi yolları hızlandırabilirim? ve bunu nasıl yapabilirim?

Dim xlApp As Microsoft.Office.Interop.Excel.Application 
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook 
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet 

xlApp = New Microsoft.Office.Interop.Excel.Application 
xlWorkBook = xlApp.Workbooks.Open("C:\Install\Data.xlsx") 
xlWorkSheet = xlWorkBook.Sheets("sheet1") 

Dim countRows As Integer = xlWorkSheet.UsedRange.Rows.Count() 

For i As Integer = 2 To countRows 
    newVersionRow = VersionDBDataSet.IEVersion.NewIEVersionRow() 
    newVersionRow.PC_Name = xlWorkSheet.Cells(i, 1).value.ToString() 
    newVersionRow.PC_Status = xlWorkSheet.Cells(i, 2).value.ToString() 
    newVersionRow.svcKBNumber = xlWorkSheet.Cells(i, 3).value.ToString() 
    newVersionRow.svcVersion = xlWorkSheet.Cells(i, 4).value.ToString() 
    newVersionRow.Last_Updated = DateTime.Parse(xlWorkSheet.Cells(i, 5).value.ToString()) 
    newVersionRow.Patches = Integer.Parse(xlWorkSheet.Cells(i, 6).value) 
    newVersionRow.Uptime = Integer.Parse(xlWorkSheet.Cells(i, 7).value) 
    newVersionRow.Count = Integer.Parse(xlWorkSheet.Cells(i, 8).value) 
    newVersionRow.Offline = Integer.Parse(xlWorkSheet.Cells(i, 9).value) 

    VersionDBDataSet.IEVersion.Rows.Add(newVersionRow) 

    If newVersionRow.PC_Status = "Online" Then 
     numofOnline += 1 
     lblOnlinePC.Text = numofOnline 
    Else 
     numofOffline += 1 
     lblOfflinePC.Text = numofOffline 
    End If 

Next 

xlWorkBook.Close() 
xlApp.Quit() 

releaseObject(xlApp) 
releaseObject(xlWorkBook) 
releaseObject(xlWorkSheet) 
+0

Şu anda nasıl yapıyor olduğunuzu yazarak kodu gönderin – Dan

+0

@Dan alright, ben kodu gönderdim –

+0

'OleDbDataReader' kullanmayı denediniz mi? – rheitzman

cevap

0

bir yolu, bir diziye kullanılan tüm hücreleri okuma dizi yineleme ve bir DataTable sıralarının içine hücre veri yerleştirmektir. Aşağıdaki üç sütun veriyi okumak için kurulum yapılır, eğer sayfada daha fazla sütun varsa, bu demoda görmezden geliriz. Yani sizin için, dokuz veri sütunu oluşturun ve aynı mantığı kullanın.

HasHeader işlevinin son bağımsız değişkeni True olarak geçtiyse, dizideki ilk satırın sütun adları olarak kabul edileceğini ve False uygulamasının ilk satırdaki verileri göstereceğini unutmayın. Bununla birlikte, kodun ilk satırda başlayacağımızı varsayarsak da, satır 4'e başlıyorsak ve dördüncü satırda sütun başlıkları varsa, bu durum yukarıdaki satırlar da toplanır ve atılır. Buradaki sihir sizin için doğru olmayabilir.

DÜZENLEME: Aynen ilk satırdan değil başlıyor görünür ancak istediğini elde etmek dizideki ilk birkaç unsurları atlamak gibi şu kabul edilebilir olmayabilir koduyla sorunuzu güncellenen gördü .

Örnek kullanım

Dim fileName As String = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Customers.xlsx") 
Dim sheetName As String = "Customers" 
Dim dtCustomers As DataTable = UsedRowsToDataTable(fileName, sheetName, True) 
DataGridView1.DataSource = dtCustomers 

Kod DataTable

Option Strict On 
Option Infer Off 

Imports Excel = Microsoft.Office.Interop.Excel 
Imports Microsoft.Office 
Imports System.Runtime.InteropServices 
Module ExcelIterataingData_DataTable 
    Public Function UsedRowsToDataTable(
     ByVal FileName As String, 
     ByVal SheetName As String, 
     ByVal HasHeader As Boolean) As DataTable 

     Dim dtSheetData As New DataTable 

     If IO.File.Exists(FileName) Then 

      Dim Proceed As Boolean = False 
      Dim xlApp As Excel.Application = Nothing 
      Dim xlWorkBooks As Excel.Workbooks = Nothing 
      Dim xlWorkBook As Excel.Workbook = Nothing 
      Dim xlWorkSheet As Excel.Worksheet = Nothing 
      Dim xlWorkSheets As Excel.Sheets = Nothing 
      Dim xlCells As Excel.Range = Nothing 

      xlApp = New Excel.Application 
      xlApp.DisplayAlerts = False 
      xlWorkBooks = xlApp.Workbooks 
      xlWorkBook = xlWorkBooks.Open(FileName) 

      xlApp.Visible = False 

      xlWorkSheets = xlWorkBook.Sheets 

      For x As Integer = 1 To xlWorkSheets.Count 
       xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet) 

       If xlWorkSheet.Name = SheetName Then 
        Proceed = True 
        Exit For 
       End If 

       Marshal.FinalReleaseComObject(xlWorkSheet) 
       xlWorkSheet = Nothing 

      Next 
      If Proceed Then 

       dtSheetData.Columns.AddRange(
        New DataColumn() _ 
        { 
         New DataColumn With 
         { 
          .ColumnName = "CompanyName", 
          .DataType = GetType(String) 
         }, 
         New DataColumn With 
         { 
          .ColumnName = "ContactName", 
          .DataType = GetType(String) 
         }, 
         New DataColumn With 
         { 
          .ColumnName = "ContactTitle", 
          .DataType = GetType(String) 
         } 
        } 
       ) 

       Dim xlUsedRange As Excel.Range = xlWorkSheet.UsedRange 

       Try 

        Dim ExcelCells(,) As Object = 
         CType(xlUsedRange.Value(
           Excel.XlRangeValueDataType.xlRangeValueDefault), 
          Object(,)) 

        If ExcelCells IsNot Nothing Then 
         ' Get bounds of the array. 
         Dim RowCount As Integer = ExcelCells.GetUpperBound(0) 

         For row As Integer = 1 To RowCount 

          If (ExcelCells(row, 1) IsNot Nothing) AndAlso (ExcelCells(row, 2) IsNot Nothing) Then 
           dtSheetData.Rows.Add(New Object() _ 
            { 
             ExcelCells(row, 1), 
             ExcelCells(row, 2), 
             ExcelCells(row, 3) 
            } 
           ) 
          End If 
         Next 

        End If 
       Finally 
        Release(xlUsedRange) 
       End Try 

      End If 

      xlWorkBook.Close() 
      xlApp.UserControl = True 
      xlApp.Quit() 

      Release(xlCells) 
      Release(xlWorkSheets) 
      Release(xlWorkSheet) 
      Release(xlWorkBook) 
      Release(xlWorkBooks) 
      Release(xlApp) 

      If Not Proceed Then 
       Throw New Exception("Failed to locate " & SheetName) 
      End If 
     Else 
      Throw New Exception("Failed to locate " & FileName) 
     End If 

     If HasHeader Then 
      If dtSheetData.Rows.Count > 0 Then 
       dtSheetData.Rows(0).Delete() 
      End If 
     End If 

     Return dtSheetData 

    End Function 
    Private Sub Release(ByVal sender As Object) 
     Try 
      If sender IsNot Nothing Then 
       Marshal.ReleaseComObject(sender) 
       sender = Nothing 
      End If 
     Catch ex As Exception 
      sender = Nothing 
     End Try 
    End Sub 

End Module 

başka seçenek veri okumak için projeyi görmek, bir MSDN code samples here örnekleri görebilirsiniz edildi OleDb veri sağlayıcı üzerinden okumaktır Basit bir örnek için Demo1_VB, diğerleri ise biraz daha karmaşıktır.