从Excel导入到SQL Server c#

时间:2016-02-10 16:07:57

标签: c# sql-server excel sqlbulkcopy import-from-excel

我正在尝试将数据从Excel文件导入SQL Server中的表,但它会抛出错误。

            string ssqltable = "mytable";

        string myexceldataquery = "select * from [Order Form$]";
        try
        {
            string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;Persist Security Info=False;data source='C:\Users\usiddiqui\Desktop\myexcel.xlsx';extended properties=" + "\'excel 12.0;hdr=yes;\';";
            string ssqlconnectionstring = "server=SANJSQL-DEV;Database=db; User Id=user; Password=pass;";

            string sclearsql = "delete from " + ssqltable;
            SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
            SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
            sqlconn.Open();
            sqlcmd.ExecuteNonQuery();
            sqlconn.Close();
            OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
            OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
            oledbconn.Open();
            OleDbDataReader dr = oledbcmd.ExecuteReader();
            SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
            bulkcopy.DestinationTableName = ssqltable;
            bulkcopy.BatchSize = 100;
            bulkcopy.WriteToServer(dr);
            //while (dr.Read())
            //{
            //    bulkcopy.WriteToServer(dr);
            //}
            dr.Close();
            oledbconn.Close();
            label1.Text = "File imported into sql server."; 
        }
        catch (Exception ex)
        {
            //handle exception 
        }

错误发生在oledbconn.Open(); 这是错误

  

无法找到可安装的ISAM。

1 个答案:

答案 0 :(得分:0)

您正在混合使用转义语法。您正在使用@切换到多行,但之后您正在使用\来逃避。不要逃避\并删除最后的\。

string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;data source=C:\Users\usiddiqui\Desktop\myexcel.xlsx;extended properties=excel 12.0;hdr=yes;";