1

我正在将一个 excel 表导入到 sql server db 表中,该表由 id | 数据(实际上是 mm/dd/yyyy 中的日期)我能够将数据导入数据库表但我希望将 Excel 表的数据(日期)列转换为 yyyy/mm/dd 格式,然后再将其导入sql服务器。这是我导入excel表的代码:

      DataTable dt7 = new DataTable();
      dt7.Load(dr);

                // Bulk Copy to SQL Server
     using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
     {                       


     bulkCopy.DestinationTableName = "ExcelTable";


     bulkCopy.WriteToServer(dt7);


     }
     dr.Close();

我找到了一段代码将 mm/dd/yyyy 转换为 yyyy/mm/dd:

    string a = "12/20/2012";
    DateTime dt = Convert.ToDateTime(a);
    string st = dt.ToString("yyyy/MM/dd");
    Label1.Text = a;
    Label2.Text = st;

但我不知道如何在我的代码中实现它。我是一个完整的新手,所以你可能不得不用代码来解释:(

4

2 回答 2

0

您必须从 DataTable 中检索所有 DataRows。选择 Date 列,修改它,放回原处。

DataRow[]  ExcelRows;
ExcelDataTable.Rows.CopyTo(ExcelRows,0);

For(int i=0;i<ExcelRows.Length;i++)//i represents the row
{
     var oldDate=ExcelRows [i]["DateColumn"].ToString();
     var newDate=Convert.ToDateTime(oldDate);   
     ExcelRows [i]["DateColumn"] = newDate.ToString("yyyy/MM/dd");   
}  

 bulkCopy.WriteToServer(ExcelRows);
于 2012-10-29T05:40:49.360 回答
0

尝试这个:

Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.Web.Configuration

//Declare Variables - Edit these based on your particular situation
Dim sSQLTable As String = "TempTableForExcelImport"
Dim sExcelFileName As String = "myExcelFile.xls"
Dim sWorkbook As String = "[WorkbookName$]"

//Create our connection strings
Dim sExcelConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(sExcelFileName) & ";Extended Properties=""Excel 8.0;HDR=YES;"""
Dim sSqlConnectionString As String = WebConfigurationManager.ConnectionStrings("MyConnectionString").ToString


//Series of commands to bulk copy data from the excel file into our SQL table
Dim OleDbConn As OleDbConnection = New OleDbConnection(sExcelConnectionString)
Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM " & sWorkbook), OleDbConn)
OleDbConn.Open()
Dim dr As OleDbDataReader = OleDbCmd.ExecuteReader()


Using bulkCopy As New System.Data.SqlClient.SqlBulkCopy(con) 
bulkCopy.DestinationTableName = "tblExcel" 

//Define ColumnMappings: source(Excel) --destination(DB Table column)   
bulkCopy.ColumnMappings.Add("col1", "col1") 
bulkCopy.ColumnMappings.Add("col2", "col2") 
:
:
bulkCopy.ColumnMappings.Add("col2", ExcelRows [i]["DateColumn"].ToString("yyyy/MM/dd")) //This is for date

bulkCopy.WriteToServer(dr) 

End Using 
bulkCopy.WriteToServer(dr)
OleDbConn.Close()
于 2012-10-29T05:56:10.513 回答