带换行符和回车符的SqlBulkCopy

时间:2013-08-20 02:49:44

标签: sql-server sqlbulkcopy

我正在使用SqlBulkCopy将Excel数据导入mssql。 我在Excel中有很多行数据,有2列,内容有换行符和回车符(我从下面的在线阅读中理解为真)

Chr(10) == vbLF == Line Feed (LF)
Chr(13) == vbCR == Carriage Return (CR)
Chr(13) & Chr(10) == vbCrLf == Carriage Return/Line Feed

SqlBulkCopy工作正常但我想保留在导入到mssql时Excel单元格中的回车符/换行符。目前它是作为长字符串插入的。

实施例: 其中一个单元格的内容如下[单个单元格中的多行]。

1st line in cell 1
2nd line in cell 1

当我使用SqlBulkCopy将Excel数据导入mssql时,上面的状态列将作为

插入
"1st line in cell 12nd line in cell 1"

如何从Excel单元格中保留“回车符/换行符”,以便将其插入数据库中,如下所示?

1st line in cell 1
2nd line in cell 1

以下是我的代码。

Dim conectionstring As String = ""
If strExt.ToLower() = ".xls" Then
    conectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Excel & ";Extended Properties=Excel 8.0"
ElseIf strExt.ToLower() = ".xlsx" Then
    conectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Excel & ";Extended Properties=Excel 12.0"
End If
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection(conectionstring)
ExcelConnection.Open()
Dim expr As String = "SELECT * FROM [Sheet1$] where not U_Id is null"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection)
Dim objDR As OleDbDataReader
Dim SQLconn As New SqlConnection()

SQLconn.ConnectionString = ConnString
SQLconn.Open()

Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLconn)

    bulkCopy.DestinationTableName = "SL_DataInfo_Temp"
    bulkCopy.ColumnMappings.Add("U_Id", "di_id")
    bulkCopy.ColumnMappings.Add("File_Ref", "di_fileRef")
    bulkCopy.ColumnMappings.Add("Date", "di_date")
    bulkCopy.ColumnMappings.Add("Status", "di_status")

    objDR = objCmdSelect.ExecuteReader

    If objDR.HasRows Then ''And objDR.FieldCount >= 13 Then
        bulkCopy.WriteToServer(objDR)
        ExcelConnection.Close()
        SQLconn.Close()
    End If 
End Using

0 个答案:

没有答案