将Access查询结果导出为csv文件

3
我有一个访问数据库,可以操作来自Magento电子商店的数据,重新格式化数据,然后(希望!)生成CSV文件,可导入到eBay Turbolister,以进行批量上传到eBay。
我已经创建了一个查询,可以将数据正确地布局为Turbolister所需的格式。但是我的问题很多(包括一些似乎与Access处理大字段内容有关的问题),无法正常工作的简单脚本是导出查询结果作为格式正确的CSV文件,需要在文本值内部对双引号进行加倍(即如果该值本身包含需要保留的引号)。
DoCmd.TransferText解决方案会引发与字段大小相关的错误(“字段太小,无法接受您尝试添加的数据量”),所以不行。
是否有人能提供VBA中有效的CSV导出程序呢?
谢谢!

1
你看过使用 schema.ini (http://stackoverflow.com/questions/13255004/exporting-data-into-a-preformatted-file/13255522#13255522) 吗? - Fionnuala
别忘了你可以在查询中使用 replace 函数 -- replace(myfield,"""","""""") -- 你可以将这个函数用于任何需要导出文本字段的查询。 - Fionnuala
1个回答

2

这是我有时候会使用的一个旧函数,它允许您指定分隔符,还检查它输出的数据,如果无法评估为日期或数字等,则使用双引号:

Public Function ExportTextDelimited(strQueryName As String, strDelimiter As String)

Dim rs          As Recordset
Dim strHead     As String
Dim strData     As String
Dim inti        As Integer
Dim intFile     As Integer
Dim fso         As New FileSystemObject

On Error GoTo Handle_Err

    fso.CreateTextFile ("C:\Untitled.csv")

    Set rs = Currentdb.OpenRecordset(strQueryName)

    rs.MoveFirst

    intFile = FreeFile
    strHead = ""

    'Add the Headers
    For inti = 0 To rs.Fields.Count - 1
        If strHead = "" Then
            strHead = rs.Fields(inti).Name
        Else
            strHead = strHead & strDelimiter & rs.Fields(inti).Name
        End If
    Next

    Open "C:\Untitled.csv" For Output As #intFile

    Print #intFile, strHead

    strHead = ""

    'Add the Data
    While Not rs.EOF

        For inti = 0 To rs.Fields.Count - 1
            If strData = "" Then
                strData = IIf(IsNumeric(rs.Fields(inti).value), rs.Fields(inti).value, IIf(IsDate(rs.Fields(inti).value), rs.Fields(inti).value, """" & rs.Fields(inti).value & """"))
            Else
                strData = strData & strDelimiter & IIf(IsNumeric(rs.Fields(inti).value), rs.Fields(inti).value, IIf(IsDate(rs.Fields(inti).value), rs.Fields(inti).value, """" & rs.Fields(inti).value & """"))
            End If
        Next

        Print #intFile, strData

        strData = ""

        rs.MoveNext
    Wend

        Close #intFile

rs.Close
Set rs = Nothing

'Open the file for viewing
Application.FollowHyperlink "C:\Untitled.csv"   

Exit Function

Handle_Err:
MsgBox Err & " - " & Err.Description

End Function

这可能需要进行一些微调,因为我已经去掉了一些仅适用于我的特定情况的部分,但这可能是一个起点。


谢谢。即使这个程序已经很努力地处理了同时存在逗号和引号的文本字段,但我会尝试稍微调整一下。我会告诉你我的进展情况。 - cheshirepine
@cheshirepine 抱歉我错过了那一点,你的数据中不应该包含你计划使用的分隔符,因为这会使事情变得复杂,通常这就是为什么 CSV 不是最好的格式的原因 :( - Matt Donnan
是的,我意识到了。但是当你的数据包含用引号括起来的类标签的HTML时,而CSV是你唯一可用于导入到Turbolister的选项时,你的选择就有点有限了! :D 不过我正在逐个解决它们。 - cheshirepine
@cheshirepine 我猜为了让事情更加复杂,你的电子商务店没有其他数据选项可用? - Matt Donnan
我已经在查看XML导出,但这对于导入到Turbolister并没有真正帮助,因为Turbolister仅接受特定结构的CSV。XML导出更整洁,但在传输到TL时仍然存在相同的问题.... :( - cheshirepine
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接