将数据从Excel导入到Sql Server 2008#2

时间:2014-01-24 05:05:38

标签: c# sql sql-server excel oledb

string path = string.Concat(Server.MapPath("~/TempFiles/"), FileUpload1.FileName);
//Save File as Temp then you can delete it if you want 
FileUpload1.SaveAs(path);


string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);

// Create Connection to Excel Workbook 
using (OleDbConnection connection =
             new OleDbConnection(excelConnectionString))
{
    OleDbCommand command = new OleDbCommand
            ("Select * FROM [Sheet1$]", connection);

    connection.Open();

    // Create DbDataReader to Data Worksheet 
    using (DbDataReader dr = command.ExecuteReader())
    {

        // SQL Server Connection String 
        string sqlConnectionString = @conn;

        // Bulk Copy to SQL Server 
        using (SqlBulkCopy bulkCopy =
                   new SqlBulkCopy(sqlConnectionString))
        {
            bulkCopy.DestinationTableName ="Table1";
            bulkCopy.WriteToServer(dr);
            Label1.Text = "The Client data has been exported successfully from Excel to SQL";
        }
    }
}

我正在尝试将数据从excel导入到SQL Server,它工作正常,直到我没有传递日期,但现在我想将日期传递给SQL Server,它提供错误,因为数据类型不匹配。

任何人都有逻辑或请建议我能做些什么......

3 个答案:

答案 0 :(得分:0)

从excel读取的DateTime是OLE自动化日期,在插入sql server之前必须将其转换为c#DateTime。从excel读取日期时,它将是双倍值。您可以使用DateTime.FromOADate将double值转换为DateTime。您可以使用SqlBulkCopy.WriteToServer(DataTable table),此方法允许您传递数据表。您可以使用require格式更改数据表中的日期,并使用它来在sql server中保存批量数据。您可以将Excel数据导入数据表,article可以为您提供帮助。

DateTime dt = DateTime.FromOADate(double.Parse(stringVariableContainingDateTime));

答案 1 :(得分:0)

Excel表格中的列可能不是有效的日期格式。

将其更改为日期类型。

Select the Column in the Excel Sheet -> Right Click -> Format Cells ->
Number Tab -> Select Date -> Choose your desired Type -> Ok 

然后你尝试导入......

答案 2 :(得分:0)

它的工作方式我尝试将其转换为datatble den change数据类型,然后插入

 string sqlConnectionString = @conn;
command.CommandType = CommandType.Text;
                OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(command);
                DataTable dt = new DataTable();
                DataSet objDataset1 = new DataSet();

                objAdapter1.Fill(dt);

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[0][5].ToString() != "")
                    {
                        DateTime dt1 = cf.texttodb(dt.Rows[0][5].ToString());
                        dt.Rows[i][5] = dt1;
                    }}
 using (SqlBulkCopy bulkCopy =
                               new SqlBulkCopy(sqlConnectionString))
                {
                    bulkCopy.DestinationTableName = "Tablename";
                    bulkCopy.WriteToServer(dt);
                    Label1.Text = "The Client data has been exported successfully from Excel to SQL";
                }

在这里我创建了一个函数txtdob,它将我的字符串转换为日期时间格式 谢谢 如果你觉得如此标记为答案我试过它