How efficient excel in C # imports SQL Server

Source: Internet
Author: User
Tags ole

Quickly inserting Excel data from OLE DB into SQL Server, where many people stitch sql through loops, this is not only error-prone but inefficient, the best way is to use bcp, or System.Data.SqlClient.SqlBulkCopy class to implement. Not only is it fast, but the code is simple, the following test code imports a sheet of more than 60,000 data, including read (slow read all) in my development environment only need about 10 seconds, and the real import process takes only 4.5 seconds.

Using System;
Using System.Data;
Using System.Windows.Forms;
Using System.Data.OleDb;
Namespace WindowsApplication2
{
public partial class Form1:form
{
Public Form1 ()
{
InitializeComponent ();
}
private void Button1_Click (object sender, EventArgs e)
{
Test to import Sheet1 from Excel into SQL Server
String connstring = "Server=localhost;uid=sa;pwd=sqlgis;database=master";
System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog ();
if (FD. ShowDialog () = = DialogResult.OK)
{
TransferData (FD. FileName, "Sheet1", connstring);
}
}
public void TransferData (string excelfile, String sheetname, String connectionString)
{
DataSet ds = new DataSet ();
Try
{
Get all the data
String strconn = "Provider=Microsoft.Jet.OLEDB.4.0 +" + "Data source=" + Excelfile + ";" + "Extended properties=excel 8.0;" ;
OleDbConnection conn = new OleDbConnection (strconn);
Conn. Open ();
String strexcel = "";
OleDbDataAdapter mycommand = null;
Strexcel = string. Format ("select * from [{0}$]", sheetname);
mycommand = new OleDbDataAdapter (Strexcel, strconn);
Mycommand.fill (ds, SheetName);
Created if the target table does not exist
String strSQL = String. Format ("If object_id" ('{ 0}') is null CREATE TABLE {0} (", sheetname);
foreach (System.Data.DataColumn C in DS. Tables[0]. Columns)
{
strSQL = = String. Format ("[{0}] varchar (255),", c.columnname);
}
strSQL = Strsql.trim (',') + ")";
using (System.Data.SqlClient.SqlConnection sqlconn = new System.Data.SqlClient.SqlConnection (connectionString))
{
Sqlconn. Open ();
System.Data.SqlClient.SqlCommand command = sqlconn. CreateCommand ();
Command.commandtext = strSQL;
Command. ExecuteNonQuery ();
Sqlconn. Close ();
}
Importing data with bcp
using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy (connectionString))
{
Bcp. Sqlrowscopied + = new System.Data.SqlClient.SqlRowsCopiedEventHandler (bcp_sqlrowscopied);
Bcp. BatchSize = 100;//number of rows per transmission
Bcp. Notifyafter = number of rows 100;//progress prompts
Bcp. DestinationTableName = sheetname;//target table
Bcp. WriteToServer (ds. Tables[0]);
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show (ex. message);
}
}
Progress display
void Bcp_sqlrowscopied (object sender, System.Data.SqlClient.SqlRowsCopiedEventArgs e)
{
This. Text = E.rowscopied.tostring ();
This. Update ();
}
}
}

The above transferdata can be used directly, if you want to think about it, you can use OLE DB to get the table structure of Excel, and add columnmappings to set the control field, The effect is exactly the same as the SQL Server DTS.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.