导出和导入DataFrames到Access文件(.mdb)

时间:2017-03-29 15:35:12

标签: python pandas ms-access

我想从Access文件(.mdb)中读取7个表,然后我需要使用pandas DataFrame更改值,然后将它们再次保存在新的Access文件中。你有什么建议怎么做吗? 我在python中相对较新,并且非常感谢任何支持。

2 个答案:

答案 0 :(得分:1)

我认为你应该检查一下。

https://pypi.python.org/pypi/pyodbc/

此外,要从Access Table读取数据,请尝试这样的操作。

# -*- coding: utf-8 -*-
import pypyodbc
pypyodbc.lowercase = False
conn = pypyodbc.connect(
    r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
    r"Dbq=C:\Users\Public\Database1.accdb;")
cur = conn.cursor()
cur.execute("SELECT CreatureID, Name_EN, Name_JP FROM Creatures");
while True:
    row = cur.fetchone()
    if row is None:
        break
    print(u"Creature with ID {0} is {1} ({2})".format(
        row.get("CreatureID"), row.get("Name_EN"), row.get("Name_JP")))
cur.close()
conn.close()

或者。 。 。如果您已经在使用Access,请使用VBA。

Dim outputFileName As String
outputFileName = CurrentProject.Path & "\Export_" & Format(Date, "yyyyMMdd") & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table1", outputFileName , True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table2", outputFileName , True

这也可以是一个选项。 。 。

strPath = "V:\Reports\Worklist_Summary.xlsx"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qryEscByDate", strPath
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qryCreatedByDate", strPath
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qryClosedByDate", strPath
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qryCreatedByUsers", strPath
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qrySummaries", strPath

或者。 。 。运行一些VBA脚本。 。

Option Compare Database
Option Explicit
Private Sub Command2_Click()
  Dim strFile As String
  Dim varItem As Variant

    strFile = InputBox("Designate the path and file name to export to...", "Export")

    If (strFile = vbNullString) Then Exit Sub

    For Each varItem In Me.List0.ItemsSelected
        DoCmd.TransferSpreadsheet transferType:=acExport, _
                                  spreadsheetType:=acSpreadsheetTypeExcel9, _
                                  tableName:=Me.List0.ItemData(varItem), _
                                  fileName:=strFile
    Next

    MsgBox "Process complete.", vbOKOnly, "Export"
End Sub
Private Sub Form_Open(Cancel As Integer)
  Dim strTables As String
  Dim tdf As TableDef


    For Each tdf In CurrentDb.TableDefs
        If (Left(tdf.Name, 4) <> "MSys") Then
            strTables = strTables & tdf.Name & ","
        End If
    Next
    strTables = Left(strTables, Len(strTables) - 1)

    Me.List0.RowSource = strTables
End Sub

导出所有数据后,执行转换并加载(返回Access或其他目标)。

我敢打赌你甚至不需要出口步骤。你可以在Access中完成你需要做的所有事情。

答案 1 :(得分:0)

这可能有所帮助:https://pypi.python.org/pypi/pandas_access

在您将表格加载到pandas数据框后,一切都应该是直截了当的。然后执行您需要的数据操作并发送回Access。