Arbaaz
Arbaaz

Reputation: 321

Converting date from mm/dd/yyyy which is read from excel to yyyy/mm/dd before sending it to database

I am importing an Excel sheet into a SQL Server database. I am able to upload the data but there is a column in Excel which consists of dates in format mm/dd/yyyy. I want this to be converted to yyyy/mm/dd before sending it to database :

DataTable dt7 = new DataTable();
dt7.Load(dr);
DataRow[] ExcelRows = new DataRow[dt7.Rows.Count];

// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
  bulkCopy.DestinationTableName = "ExcelTable";
  dt7.Rows.CopyTo(ExcelRows, 0);

  for (int i = 0; i < ExcelRows.Length; i++)
  {
    DateTime oldDate =Convert.ToDateTime(ExcelRows[i]["data"]).Date;
    DateTime newDate = Convert.ToDateTime(oldDate).Date;
    ExcelRows[i]["data"] = newDate.ToString("yyyy/MM/dd");
  }
  bulkCopy.WriteToServer(ExcelRows);

Error at: DateTime oldDate = Convert.ToDateTime(ExcelRows[i]["data"]).Date;
Error: Object cannot be cast from DBNull to other types.

It seems to me that it is reading wrong column or something since it says cannot be cast from DBnull. The Excel sheet has two columns:

id | data (which is date)

I have tried replacing ExcelRows[i]["data"] with ExcelRows[i][1] but I got the same error.

Upvotes: 0

Views: 4043

Answers (1)

Terrence Tan
Terrence Tan

Reputation: 532

This happens because ExcelRows[i]["data"] returns DBNull.

You should handle it when that happens

    if (ExcelRows[i]["data"] == DBNull.Value)
    {
        // Include any actions to perform if there is no date
    }
    else
    {
        DateTime oldDate = Convert.ToDateTime(ExcelRows[i]["data"]).Date;
        DateTime newDate = Convert.ToDateTime(oldDate).Date;
        ExcelRows[i]["data"] = newDate.ToString("yyyy/MM/dd");
    }

Upvotes: 2

Related Questions