在将csv文件导入到SQL Server DB时指定文本限定符

时间:2018-08-29 14:45:14

标签: sql-server csv import delimiter

我有一个用逗号分隔的csv文件,问题是在列中也有一个逗号。

TEXT,["pn","service"]

TEXT在一个列中,["pn","service"]在另一列中。

如何使用文本限定符正确地分隔列? enter image description here

1 个答案:

答案 0 :(得分:1)

我最近不得不处理这个问题,并提供给字段包装标识符。我修改了下面的宏以通过管道而不是引用分隔。超级用户帖子具有更多选项。 检出https://support.microsoft.com/en-us/help/291296/procedure-to-export-a-text-file-with-both-comma-and-quote-delimiters-ihttps://superuser.com/questions/130592/how-do-you-force-excel-to-quote-all-columns-of-a-csv-file

已根据@Larnu的建议进行了更新-在导入数据以进行一次卸载之前,我要使用它们重新包装一些数据文件。请小心小心,直接在excel中打开CSV ...您可能会看到值更改。

Sub PipeCommaExport()
   ' Dimension all variables.
   Dim DestFile As String
   Dim FileNum As Integer
   Dim ColumnCount As Integer
   Dim RowCount As Integer

   ' Prompt user for destination file name.
   DestFile = InputBox("Enter the destination filename" _
      & Chr(10) & "(with complete path):", "Quote-Comma Exporter")

   ' Obtain next free file handle number.
   FileNum = FreeFile()

   ' Turn error checking off.
   On Error Resume Next

   ' Attempt to open destination file for output.
   Open DestFile For Output As #FileNum

   ' If an error occurs report it and end.
   If Err <> 0 Then
      MsgBox "Cannot open filename " & DestFile
      End
   End If

   ' Turn error checking on.
   On Error GoTo 0

   ' Loop for each row in selection.
   For RowCount = 1 To Selection.Rows.Count

      ' Loop for each column in selection.
      For ColumnCount = 1 To Selection.Columns.Count

         ' Write current cell's text to file with quotation marks.
         Print #FileNum, "|" & Selection.Cells(RowCount, _
            ColumnCount).Text & "|";

         ' Check if cell is in last column.
         If ColumnCount = Selection.Columns.Count Then
            ' If so, then write a blank line.
            Print #FileNum,
         Else
            ' Otherwise, write a comma.
            Print #FileNum, ",";
         End If
      ' Start next iteration of ColumnCount loop.
      Next ColumnCount
   ' Start next iteration of RowCount loop.
   Next RowCount

   ' Close destination file.
   Close #FileNum
End Sub