将excel中的大数据导入DataGridView并保存到数据库中

时间:2017-04-14 04:18:32

标签: c# sql-server excel datagridview

我在excel上有大约12,000个数据,我需要导入到DataGridView然后将其保存到SQL Server数据库。

我面临的问题是将excel数据分解为1000个数据组,并将其保存到数据库中,显而易见的是,UI冻结。现在我甚至无法想象一次导入所有12,000个数据,上帝救我了!

如何在不冻结问题的情况下完成此任务?我尝试搜索并找到有关DataGridView virtualmode属性的信息。我该如何正确实施,帮助我找到正确的方向。

1 个答案:

答案 0 :(得分:0)

'图书馆

Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Imports System.Data
Imports System.Data.Odbc
Imports System.Data.OleDb

'加载数据网格视图

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
    Dim cnn As SqlConnection
    Dim connectionString As String
    Dim sql As String

    connectionString = "data source=Excel-PC\SQLEXPRESS;" & _
    "initial catalog=NORTHWIND;Trusted_Connection=True"
    cnn = New SqlConnection(connectionString)
    cnn.Open()
    sql = "SELECT * FROM Orders"
    Dim dscmd As New SqlDataAdapter(sql, cnn)
    Dim ds As New DataSet
    dscmd.Fill(ds)
    DataGridView1.DataSource = ds.Tables(0)
    cnn.Close()

End Sub

'从数据网格视图到SQL服务器

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click


    Dim headers = (From header As DataGridViewColumn In DataGridView1.Columns.Cast(Of DataGridViewColumn)() Select header.HeaderText).ToArray
    Dim rows = From row As DataGridViewRow In DataGridView1.Rows.Cast(Of DataGridViewRow)() Where Not row.IsNewRow Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
    Dim str As String = ""
    Using sw As New IO.StreamWriter("C:\Users\Excel\Desktop\OrdersTest.csv")
        sw.WriteLine(String.Join(",", headers))
        'sw.WriteLine(String.Join(","))
        For Each r In rows
            sw.WriteLine(String.Join(",", r))
        Next
        sw.Close()
    End Using

End Sub

我不明白为什么加载过程会导致您的机器冻结。我以前从未遇到过这个问题。

如果您想快速将数据加载到SQL Server,只需使用批量插入并删除整个数据网格视图。

BULK INSERT EmployeeDB.dbo.Employees
FROM 'C:\Data\EmployeeData_c.dat'
WITH 
  (
    DATAFILETYPE = 'char',
    FIELDTERMINATOR = ',',
    ROWTERMINATOR = '\r\n'
  );

https://www.simple-talk.com/sql/learn-sql-server/bulk-inserts-via-tsql-in-sql-server/