C # efficient SQL Server Import using Excel

Source: Internet
Author: User

In SQL Server, many people concatenate SQL statements by repeating the Excel data read by oledb. This is not only error-prone but also inefficient. The best way is to use BCP, that is, system. data. sqlclient. sqlbulkcopy class. Not only fast, but alsoCodeSimple: The following test code imports a sheet with more than 60 thousand data records, including reading (all reading is slow). It takes about 10 seconds in my development environment, 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 button#click (Object sender, eventargs e)
{< br> // test, import Sheet 1 in Excel to sqlserver
string connstring = "Server = localhost; uid = sa; Pwd = sqlgis; database = Master";
system. windows. forms. openfiledialog FD = new openfiledialog ();
If (FD. showdialog () = dialogresult. OK)
{< br> transferdata (FD. filename, "sheet1", connstring);
}< BR >}

Public void transferdata (string excelfile, string sheetname, string connectionstring)
{
Dataset DS = new dataset ();
Try
{
// Obtain all 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 );

// create a table 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)
{< br> strsql + = string. format ("[{0}] varchar (255),", C. columnname);
}< br> 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 ();
}
// Use bcp to import data
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 transmitted each time
BCP. policyafter = 100; // number of rows prompted by the progress
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 need to consider it carefully, you can use oledb to obtain the Excel table structure and add columnmappings to set the control field, in this way, you can achieve the same effect as data transmission of sqlserver.

For more information about how to obtain the Excel structure, see my previousArticle

Http://blog.csdn.net/jinjazz/archive/2008/05/13/2441635.aspx

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/jinjazz/archive/2008/07/14/2650506.aspx

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.