将Excel工作表插入SQL Server数据库

时间:2012-12-05 15:18:44

标签: c# sql-server excel data-import

我正在尝试使用OleDb从Excelgridview将Excel工作表插入到SQL Server数据库中。

我使用的代码:

namespace importfromexcel
{
  public partial class Form1 : Form
  {
     SqlConnection conn = new SqlConnection("Data Source=HAMNDOSH-PC\\SQLEXPRESS;Initial    Catalog=mohammed;Integrated Security=True");
  //  SqlCommand cmd;

     public Form1()
     {
        InitializeComponent();
     }

     OpenFileDialog ofd = new OpenFileDialog();

     private void button2_Click(object sender, EventArgs e)
     {
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            textBox1.Text = ofd.FileName;
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;data source=" + ofd.FileName + @";Extended Properties=Excel 8.0;";
        // Create Connection to Excel Workbook

        //We can Import excel to sql server like this
        using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
        {
            OleDbCommand command = new OleDbCommand("Select fname,lname FROM [sheet1$]", connection);

            connection.Open();

            // Create DbDataReader to Data Worksheet 
            using (DbDataReader dr = command.ExecuteReader())
            {
                // SQL Server Connection String 
                string sqlConnectionString = "Data Source=HAMNDOSH-PC\\SQLEXPRESS;Initial Catalog=mohammed;Integrated Security=True";
                //  SqlCommand cmd;

                // Bulk Copy to SQL Server 
                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
                {
                    bulkCopy.DestinationTableName = "test";
                    bulkCopy.WriteToServer(dr);
                }
            }
        }
    }
  }
}

我的数据库名称为:mohammed,表名为test,其中包含两列firstnamelastname,Excel表格列为fname和{ {1}} ..

问题在于,当我执行代码并从button2插入Excel工作表之后 当我点击button1时出现窗口错误

  

vshot32-clr2.exe已停止工作

有任何帮助吗?

3 个答案:

答案 0 :(得分:0)

我不知道这是否是根本原因,但是当您无法保证对话框中选择了有效文件时,您在ofd.FileName事件中引用了Click。由于您将该值存储在文本框中,我将其更改为:

string excelConnectionString = 
    @"Provider=Microsoft.Jet.OLEDB.4.0;data source=" 
          + textBox1.Text 
          + @";Extended Properties=Excel 8.0;";

在尝试实施批量复制之前,我还要验证您是否能够查询数据(例如,通过写入文本文件)作为测试。另请注意,除非您提供ColumnMapping,否则源数据必须具有完全相同的结构(包括列顺序)。

答案 1 :(得分:0)

Sql server有一个名为Sql Server Data Tools的导入工具......在那里你可以找到一个要从excel文件导入的活动......非常"最终用户"交易,我的意思是你可以在拖放的基础上配置一切...

答案 2 :(得分:0)

在excel连接字符串的扩展属性中,您可能希望设置HDR = YES和IMEX = 1。 HDR = YES将读取Excel工作表中的第一行,并将每个单元格中存储的数据作为列名称读取。 IMEX = 1告诉JET插入数据而不管每个单元格的数据类型。

看看我自己编写的这段代码,它可能对你有帮助。

        //ExcelDA Class
        public ExcelDA()
    {
        connString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + ofd.FileName + "; Extended Properties=" + '"' + "Excel 8.0; HDR=Yes; IMEX=1" + '"';
    }

    /// <summary>
    /// Method used to retrieve a datatable from excel sheet
    /// </summary>
    public DataTable GetProductsExcel()
    {
        StringBuilder excBuilder = new StringBuilder();
        excBuilder.Append("SELECT * FROM [Sheet1$];");
        //
        try
        {
            return ExecuteSqlStatement(excBuilder.ToString());
        }
        catch (Exception) 
        { 
            MessageBox.Show("Error retreiving data");
            return null;
        }
    }
    private DataTable ExecuteSqlStatement(string command)
    {
        using (OleDbConnection conn = new OleDbConnection(connString))
        {
            try
            {
                conn.Open();
                using (OleDbDataAdapter adaptor = new OleDbDataAdapter(command, conn))
                {
                    DataTable table = new DataTable();
                    adaptor.Fill(table);
                    return table;
                }
            }
            catch (SqlException e)
            {
                throw e;
            }
        }
    }
    //SqlDA class
    public void ExecuteSQLCommand(string comm)
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                conn.Open();

                using (SqlCommand command = new SqlCommand(comm, conn))
                {
                    command.ExecuteNonQuery();
                }
            }
        }
        catch (ArgumentOutOfRangeException ex)
        {
            throw ex;
        }

        catch (ArgumentException ex)
        {
            throw ex;
        }
        catch (SqlException ex) { throw ex; }
    }
    public void AddNames(string fName, string sName)
    {
          StringBuilder sqlQuery = new StringBuilder();
          //build sql insert statement here
          ExecuteSQLCommand(sqlBuilder.ToString());
    }

    //Program class
    ExcelDA reader = new ExcelDA();
    DataTable names = reader.GetSuppliersExcel();
    //string array to store excel row data for names
    string[] arr2 = new string[2] { "", ""};
        //recursive loop to retrieve each row and values from each rows columns
        foreach (DataRow row in suppliers.Rows)
        {
            for (int i = 0; i < names.Columns.Count; i++)
            {
                if (i == (names.Columns.Count - 1))
                {
                    arr2[i] = (row[i].ToString());
                }
                else
                {
                    arr2[i] = (row[i].ToString());
                }
            }
        }

            try
            {
                sql.AddNames(arr2[0], arr2[1]);
                Console.WriteLine("Added Data to SQL");
            }
            catch (Exception) { }
相关问题