利用 SqlbulkCopy 快速导入 Excel 数据至 SQLServer 数据库中

利用 SqlbulkCopy ,将Excel数据导入数据库,代码显得非常简单。更重要的是,导入速度之快、超出预期想像。

本代码环境:VS2010、Excel2007、SqlServer 2008

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;

 

namespace ImportExcelintoSQLServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

 

        private void button1_Click(object sender, EventArgs e)
        {
            string strXLSPath = "K:/Study/ImportExcelintoSQLServer/ExcelTestData.xlsx";
            string excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
                strXLSPath + ";" + "Extended Properties='Excel 12.0;HDR=YES/'";

            // Create Connection to Excel Workbook


            using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
            {
                OleDbCommand command = new OleDbCommand("Select * FROM [Sheet1$]", connection);

                connection.Open();

                // Create DbDataReader to Data Worksheet
                using (OleDbDataReader dr = command.ExecuteReader())
                {
                    // SQL Server Connection String
                    string sqlConnectionString = "Data Source=127.0.0.1;Initial Catalog=MyDB;"
                        +"Integrated Security=True";
                    // Bulk Copy to SQL Server
                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
                    {
                        bulkCopy.DestinationTableName = "ExcelData";
                        bulkCopy.WriteToServer(dr);
                    }
                }
            }
        }
    }
}

你可能感兴趣的:(利用 SqlbulkCopy 快速导入 Excel 数据至 SQLServer 数据库中)