【问题标题】:Export Access query results to csv将 Access 查询结果导出到 csv
【发布时间】:2012-11-09 14:34:57
【问题描述】:

我有一个访问数据库,它处理来自 Magento 电子商务商店的数据,重新格式化数据并(希望!)输出一个 CSV 文件,然后可以将其导入 ebay Turbolister 以大量上传到 eBay。

我已经创建了一个查询,该查询将数据正确排列为 Turbolister 所需的格式。

我的问题是多种多样的(包括一些似乎与 Access 处理大字段内容有关的问题),但是我的问题的症结在于我正在努力使用一个简单的脚本来正确导出查询结果格式化的 CSV(包括在文本值内需要加倍双引号,即如果值本身包含需要保留的引号)。

DoCmd.TransferText 解决方案引发与字段大小相关的错误(“该字段太小,无法接受您尝试添加的数据量”),所以这不好。

有没有人可以推荐一个在 VBA 中运行良好的 CSV 导出例程?

干杯

【问题讨论】:

  • 你看过使用 schema.ini (stackoverflow.com/questions/13255004/…) 吗?
  • 不要忘记您可以使用查询替换 -- replace(myfield,"""","""""") -- 您可以将它与查询中的任何文本导出字段一起使用以进行导出。

标签: vba ms-access


【解决方案1】:

这是我有时使用的一个旧函数,它允许您指定分隔符,它还检查它输出的数据,如果它不能被评估为日期或数字等,那么它使用 double引用:

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 抱歉,我错过了这一点,您的数据不应该包含您计划使用的分隔符,因为这会使事情复杂化,通常为什么 csv 不是最好的格式:(
  • 是的,我意识到这一点,但是当您的数据包含带有类标签的 HTML 时,并且 CSV 是您可以导入到 Turbolister 的唯一选项,您的选择是有限的! :D 我正在一一解决它们。
  • @cheshirepine 我猜想更复杂的是,您的电子商务商店没有其他可用的数据选项吗?
  • 我已经在查看 XML 导出,但这并不能真正帮助导入 Turbolister,它只接受预定结构的 CSV。 XML 导出更整洁,但在转移到 TL 时我仍然遇到同样的问题.... :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多