2014-11-06 61 views
1

重新說明問題...下面的代碼將數據插入到SQL Server數據庫中,然後插入正確的表中,但數據未正確插入...這裏是代碼將文件上傳到SQL Server

if (FileUpload1.HasFile) 
{ 
    string path = string.Concat((Server.MapPath("~/temp/" + FileUpload1.FileName))); 
    FileUpload1.PostedFile.SaveAs(path); 

    OleDbConnection OleDbcon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";"); 
    OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", OleDbcon); 
    OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd); 

    OleDbcon.Open(); 

    DbDataReader dr = cmd.ExecuteReader(); 
    string con_str = @"Data Source=ENERGYSQL\ENERGY;Initial Catalog=ProjectHandler;Persist Security Info=True;User ID=aconyon;Password=birchall"; 

    SqlBulkCopy bulkInsert = new SqlBulkCopy(con_str); 
    bulkInsert.DestinationTableName = "StockTable"; 
    bulkInsert.WriteToServer(dr); 

    OleDbcon.Close(); 

    Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete); 
    //Label1.ForeColor = Color.Green; 
    Label1.Text = "Successfully inserted"; 
} 
else 
{ 
    //Label1.ForeColor = ConsoleColor.Red; 
    Label1.Text = "please select ther File"; 
} 

這段代碼所做的是選擇最右邊的列,在我的示例Quantity中,並將其僅插入數據庫,忽略所有其他行(A和B),是否需要更改OleDbCommand以選擇某些行。 A(ItemName),B(Date),C(Quantity)

+0

什麼是內部異常,這可能會給你更多關於是什麼導致它的細節。 – 2014-11-06 11:57:55

+0

解決了它我認爲,剛剛得到了一個錯誤,數據庫將DateTime轉換爲int現在...使用這個:OleDbConnection OleDbcon = new OleDbConnection(@「Provider = Microsoft.Jet.OLEDB.4.0; Data Source =」+ path +「 ; Extended Properties = \「Excel 8.0; HDR = Yes; IMEX = 1 \」;「); – Crezzer7 2014-11-06 11:59:35

+0

在您的電腦上安裝微軟accsess。 – 2014-11-06 12:12:16

回答

3

使用此代碼。

string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data 
Source={0};Extended Properties='Excel 8.0;HRD=YES;IMEX=1'", 
Server.MapPath(@"~\DownloadedExcelFilesOp4\myfile" + fileExt));// + "\\" + 
FileUploadControl.PostedFile.FileName.ToString()); 
using (OleDbConnection connection = new OleDbConnection(excelConnectionString)) 
{ 
    OleDbCommand command = new OleDbCommand(("Select [Demo1] ,[Demo2] FROM [Sheet1$]"), 
    connection); 
    connection.Open(); 
    using (DbDataReader dr = command.ExecuteReader()) 
    { 
    } 
} 
+0

工作了一種享受,謝謝朋友 – Crezzer7 2014-11-06 12:19:20

-3

您可以使用類似下面的查詢來獲取任何特定列的值。

OleDbCommand command = new OleDbCommand(("Select [Col1] ,[Col2] FROM [Sheet1$]"), 
    connection);