简体   繁体   中英

Uploading a file into SQL Server

Reword the question... the below code inserts the data into an SQL Server database, and into the correct table however, the data is not inserted correctly... here is the code

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";
}

what this code does is select the far most right column, in my example Quantity, and insert just this into the database, ignoring all other rows (A and B) do i need to change the OleDbCommand to select certain rows. A(ItemName), B(Date), C(Quantity)

use this code.

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())
   {
   }
}

You can use query like below to get the value of any particular column.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM