0

我正在将 Excel 工作表导入 SQL Server 数据库。我可以上传数据,但 Excel 中有一个包含日期格式的列mm/dd/yyyy。我希望yyyy/mm/dd在将其发送到数据库之前将其转换为:

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);

错误:DateTime oldDate = Convert.ToDateTime(ExcelRows[i]["data"]).Date;
错误:无法将对象从 DBNull 转换为其他类型。

在我看来,它正在阅读错误的专栏或其他内容,因为它说cannot be cast from DBnull。Excel 工作表有两列:

id | data (which is date)

我尝试替换ExcelRows[i]["data"]为,ExcelRows[i][1]但我得到了同样的错误。

4

1 回答 1

2

这是因为 ExcelRows[i]["data"] 返回 DBNull。

发生这种情况时你应该处理它

    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");
    }
于 2012-10-30T05:39:45.190 回答