2014-02-10 223 views
2

如何將數據從Excel工作表導入SQL Server數據庫在asp網絡中?從Excel工作表導入數據到SQL Server數據庫

Dim OleDbcon As New OleDbConnection((Convert.ToString("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=") & path) + ";Extended Properties=Excel 12.0;") 

Dim cmd As New OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon) 
Dim objAdapter1 As New OleDbDataAdapter(cmd) 

OleDbcon.Open() 
Dim dr As DbDataReader = cmd.ExecuteReader() 

Dim con_str As String = "Data Source=.;Initial Catalog=studentdetails;Integrated Security=True" 

' Bulk Copy to SQL Server 
Dim bulkInsert As New SqlBulkCopy(con_str) 
bulkInsert.DestinationTableName = "Table name" 
bulkInsert.WriteToServer(dr) 
OleDbcon.Close()e here 
+0

推動這一數據到SQL數據庫表請點擊此鏈接[stackoverflow.com](http://stackoverflow.com/questions/12378705/importing-excel-to-sql-database-using -vb-net-and-asp-net) –

+0

檢查這個答案太http://stackoverflow.com/questions/10447015/uploading-an-excel-sheet-and-importing-the-data-into-sql-server-數據庫 –

回答

5

將其分爲兩個步驟:

1)地方保存文件 - 這是非常普遍的看到這一點:

串saveFolder = @ 「C:\ TEMP \上傳」; //在你的機器上挑選一個文件夾來存儲上傳的文件

string filePath = Path.Combine(saveFolder,FileUpload1.FileName);

FileUpload1.SaveAs(filePath); 現在你有你的文件在本地,真正的工作可以完成。

2)從文件中獲取數據。您的代碼應該按原樣工作,但您可以簡單地使用以下方式編寫連接字符串:

string excelConnString = String.Format(「Provider = Microsoft.Jet.OLEDB.4.0; Data Source = {0}; Extended Properties =」 Excel 12.0「;」,filePath); 然後,您可以考慮刪除剛剛上傳和導入的文件。

爲了提供更具體的例子,我們可以重構你的代碼的兩種方法:

private void SaveFileToDatabase(string filePath) 
{ 
    String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True"; 

    String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath); 
    //Create Connection to Excel work book 
    using (OleDbConnection excelConnection = new OleDbConnection(excelConnString)) 
    { 
     //Create OleDbCommand to fetch data from Excel 
     using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection)) 
     { 
      excelConnection.Open(); 
      using (OleDbDataReader dReader = cmd.ExecuteReader()) 
      { 
       using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection)) 
       { 
        //Give your Destination table name 
        sqlBulk.DestinationTableName = "Excel_table"; 
        sqlBulk.WriteToServer(dReader); 
       } 
      } 
     } 
    } 
} 


private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl) 
{ 


    string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName); 

    fileUploadControl.SaveAs(filePath); 

    return filePath; 

} 

你可以簡單地再調用SaveFileToDatabase(GetLocalFilePath(@ 「C:\ TEMP \上傳」,FileUpload1));

請考慮查看Excel連接字符串的其他擴展屬性。他們進來有用!

您可能想要做的其他改進包括將您的Sql數據庫連接字符串放入配置中,並添加適當的異常處理。請考慮這個例子僅用於演示!

+0

對不起,我只能用C#來幫助你。 –

+0

按照原樣進行更改以適應我的需求。美麗。謝謝!
更改連接以從Appconfig中檢索 – PCPGMR

+0

檢查此答案http://stackoverflow.com/questions/10447015/uploading-an-excel-sheet-and-importing-the-data-into-sql-server-database –

-2

添加一個DataTable,它可以保存通過OLEDb生成的Excel數據。

string excelconnectionstring = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text;Jet OLEDB:Max Buffer Size=256;"); 

using (OleDbConnection oledbconn = new OleDbConnection(excelconnectionstring)) 
    { 
        using (OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn)) 
        { 
         oledbconn.Open(); 
         OleDbDataReader dr = oledbcmd.ExecuteReader(); 


         dtBulkUpload.Load(dr); 
} 
} 

然後將此DataTable序列化爲可發送到SQL存儲過程的XML。這種做法是非常有用的,如果有太多的領域,你可以把所有在一個單一的參數

using (StringWriter strXML = new StringWriter()) 
{ 
    dtBulkUpload.TableName = "BulkUpload"; 
    dtBulkUpload.WriteXml(strXML, XmlWriteMode.IgnoreSchema, false); 
    xmlString = strXML.ToString(); 
}          



using (SqlCommand cmd = new SqlCommand("Stored PROC Name")) 
{ 
    cmd.Parameters.AddWithValue("@dtBulkUpload", bulkUploadData); 
         //SqlParameter returnParameter = cmd.Parameters.Add("@result", SqlDbType.NVarChar); 
         //returnParameter.Direction = ParameterDirection.Output; 
         cmd.Parameters.Add("@result", SqlDbType.NVarChar,3000); 
         cmd.Parameters["@result"].Direction = ParameterDirection.Output; 

         cmd.Connection = con; 
         cmd.CommandType = CommandType.StoredProcedure; 

         con.Open(); 
         cmd.ExecuteNonQuery(); 
         query = (string)(cmd.Parameters["@result"].Value.ToString()); 
         con.Close(); 
+0

您正在使用「dtBulkUpload」對象,它在代碼中的任何地方都沒有初始化 –

0

,我們將創建中,我們將精益求精,數據表或數據後設定的紙信息的方法數據表我們將使用SQL批量

protected void Button1_Click(object sender, EventArgs e) 
{ 
try 
{ 
SqlConnection con = new SqlConnection(@"Data 
Source=SANI2711\SQLEXPRESS;Initial Catalog=customer;Integrated 
Security=True;"); 
con.Open(); 
DataTable dt = new DataTable(); 
dt = DataExcel(); 
if (dt.Rows.Count > 0) 
{ 
for() 
} 
} 
catch(Exception ex) 
{ 
Response.Write(ex); 
} 
} 
protected void Button2_Click(object sender, EventArgs e) 
{ 
try 
{ 
SqlConnection con = new SqlConnection(@"Data 
Source=SANI2711\SQLEXPRESS;Initial Catalog=customer;Integrated 
Security=True;"); 
con.Open(); 
DataTable dt = new DataTable(); 
dt = DataExcel(); 
if (dt.Rows.Count > 0) 
{ 
SqlBulkCopy objbulk = new SqlBulkCopy(con); 
objbulk.DestinationTableName = "customer1"; 
objbulk.ColumnMappings.Add("CustomerID", "CustomerID"); 
objbulk.ColumnMappings.Add("City", "City"); 
objbulk.ColumnMappings.Add("Country", "Country"); 
    objbulk.ColumnMappings.Add("PostalCode", "PostalCode"); 
    objbulk.WriteToServer(dt); 
    } 
} 
catch (Exception ex) 
{ 
Response.Write(ex); 
} 
} 
protected DataTable DataExcel() 
{ 
DataTable dt = new System.Data.DataTable(); 
try 
{ 
string [email protected]"C:\Users\sani singh\Documents\Excel03.xls"; 
string sWorkbook = "[Sheet1$]"; 
string [email protected]"Provider=Microsoft.Jet.OLEDB.4.0;Data 
Source="+filenname+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; 
OleDbConnection OleDbConn = new OleDbConnection(ExcelConnectionString); 
OleDbConn.Open(); 
OleDbCommand OleDbCmd = new OleDbCommand(("SELECT * FROM " + sWorkbook), 
OleDbConn); 
DataSet ds = new DataSet(); 
OleDbDataAdapter sda = new OleDbDataAdapter(OleDbCmd); 
sda.Fill(ds); 
dt = ds.Tables[0]; 
OleDbConn.Close(); 
} 
catch(Exception ex) 
{ 
Response.Write(ex); 
} 
return dt; 
} 
} 
} 
相關問題