SqlBulkCopy - Add rows along with additional values to database

ado.net asp.net c# sqlbulkcopy sql-server

Question

I am trying a code snippet that add excel data into sql database using SqlBulkCopy. The code snippet is as given below

OleDbConnection connection=null;
        string FilePath="";
         try
            {
                if (FileUpload1.HasFile)
                {
                    FileUpload1.SaveAs(Server.MapPath("~/UploadedFolder/"+FileUpload1.FileName));
                    FilePath = Server.MapPath("~/UploadedFolder/"+FileUpload1.FileName);
         
                }

                string path = FilePath;
                // Connection String to Excel Workbook
                string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);
                connection = new OleDbConnection();
                connection.ConnectionString = excelConnectionString;
                OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
                connection.Open();
                // Create DbDataReader to Data Worksheet
                DbDataReader dr = command.ExecuteReader();

                // SQL Server Connection String
                string sqlConnectionString = @"Data Source=sample;Initial Catalog=ExcelImport;User ID=sample;Password=sample";

                // Bulk Copy to SQL Server 
                SqlBulkCopy bulkInsert = new SqlBulkCopy(sqlConnectionString);
                bulkInsert.DestinationTableName = "Customer_Table";
                bulkInsert.WriteToServer(dr);
           
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            finally
            {
                connection.Close();
                Array.ForEach(Directory.GetFiles(Server.MapPath("~/UploadedFolder/")), File.Delete);
            }

This add the data from excel file to sql server database table. But my requirement is that I need to add the values of excel sheet plus additionally my own values say autogenerated studentid.

So my question is how I will add new values (say studentid, batchcode etc) along with values that read from excel. And these values to be added to each row of excel data.

Example:-

excel contains following columns

CustomerID,City,Country,PostalCode

Now I need to add values to sql server by adding some new columns as

StudentID,CustomerID,BatchCode,City,Country,Email,PostalCode

How can I do it

Please help

Accepted Answer

You could do the following:

  • load the excel data into a data table,
  • Add the remaining columns to the data table,
  • Set new column values
  • SqlBulkCopy the data table into SQL Server.

Something like this:

DbDataReader dr = command.ExecuteReader();

DataTable table = new DataTable("Customers");
table.Load(dr);
table.Columns.Add("StudentId", typeof(int));
table.Columns.Add("BatchCode", typeof(string));
table.Columns.Add("Email", typeof(string));

foreach (DataRow row in table.Rows)
{
    row["StudentId"] = GetStudentId(row);
    row["BatchCode"] = GetBatchCode(row);
    row["Email"] = GetEmail(row);
}


// SQL Server Connection String
string sqlConnectionString = @"Data Source=sample;Initial Catalog=ExcelImport;User ID=sample;Password=sample";

// Bulk Copy to SQL Server 
SqlBulkCopy bulkInsert = new SqlBulkCopy(sqlConnectionString);
bulkInsert.DestinationTableName = "Customer_Table";
bulkInsert.WriteToServer(table);



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why