簡體   English   中英

從Excel導入到SQL Server C#

[英]Importing from Excel to SQL Server c#

我正在嘗試將數據從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。

您正在混合轉義語法。 您使用@切換到多行,但隨后使用\\進行轉義。 不要逃避\\並刪除最后的\\。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM