【问题标题】:Transfer data from excel worksheet (openpyxl) to database table (dbf)将数据从 excel 工作表 (openpyxl) 传输到数据库表 (dbf)
【发布时间】:2019-05-29 04:15:31
【问题描述】:

我有一个读取 Excel 工作表的简单问题,将包含大约 83 列的每一行视为唯一的数据库记录,将其添加到本地数据记录并最终附加并写入 DBF 文件。

我可以从 excel 中提取所有值并将它们添加到列表中。但是列表的语法不正确,我不知道如何准备/将列表转换为数据库记录。我正在使用 Openpyxl、dbf 和 python 3.7。

目前我只是在测试并尝试为第 3 行准备数据(因此 min_max rows = 3)

我了解数据应采用以下格式 (('','','', ... 83 个条目), \ ('','','', ... 83 个条目) \ )

但我不知道如何将列表数据转换为记录 或者,或者,如何将 excel 数据直接读入 DF 可附加格式

tbl_tst.open(mode=dbf.READ_WRITE) # all fields character string

for everyrow in ws_IntMstDBF.iter_rows(min_row = 3, max_row = 3, max_col = ws_IntMstDBF.max_column-1):
    datum = [] #set([83]), will defining datum as () help solve the problem?
    for idx, cells in enumerate(everyrow):
        if cells.value is None: # for None entries, enter empty string
            datum.append("")
            continue
        datum.append(cells.value) # else enter cell values 

     tbl_tst.append(datum) # append that record to table !!! list is not record error here

tbl_tst.close()

错误是抱怨使用列表追加到表中,这应该是记录等。请指导我如何将 excel 行转换为可追加的 DBF 表数据。

raise TypeError("data to append must be a tuple, dict, record, or template; not a %r" % type(data))
TypeError: data to append must be a tuple, dict, record, or template; not a <class 'list'>

【问题讨论】:

    标签: python excel openpyxl dbf


    【解决方案1】:

    改变

    tbl_tst.append(datum)
    

    tbl_tst.append(tuple(datum))
    

    这将消除该错误。只要您的所有单元格数据都具有适当的类型,那么追加应该可以工作。

    【讨论】:

    • 嗨,Ethan,我采纳了你的建议,并且能够毫无问题地编写 DBF。额外的好处是 pyinstaller exe 功能齐全,而在我的解决方案中,pysal 在生成的 exe 中出错。我对 exe 有一个悬而未决的问题,即 ..\input\file 等相对路径在 exe 文件夹中工作正常,但绝对路径不起作用,除非我将 exe 文件移动到 src 文件夹。这是新线程的问题吗?
    • @MakJ:是的,请为此提出一个新问题。很高兴它现在对你有用!
    【解决方案2】:

    感谢您的回复,从昨晚开始,我在尝试不同的解决方案时遇到了一些问题。

    对我有用的一个解决方案如下: 我确保我使用的工作表数据都是字符串/文本,并将任何空条目转换为字符串类型并输入空字符串。所以下面的代码完成了这个任务:

    #house keeping
    for eachrow in ws_IntMstDBF.iter_rows(min_row=2, max_row=ws_IntMstDBF.max_row, max_col=ws_IntMstDBF.max_column):
        for idx, cells in enumerate(eachrow):
            if cells.value is None: # change every Null cell type to String and put 0x20 (space)
                cells.data_type = 's'
                cells.value = " "
    

    写完工作表后,我使用 panda 数据框重新打开它,并验证内容是否都是字符串类型,并且数据框中没有剩余的“nan”值。 然后我使用“Dani Arribas-Bel”中的 df2dbf 函数,对其进行修改以适应我正在使用的数据并转换为 dbf。

    导入dataframe并转换为dbf格式的代码如下:

    abspath = Path(__file__).resolve() # resolve to relative path to absolute
    rootpath = abspath.parents[3] # root (my source file is3 sub directories deep
    xlspath = rootpath / 'sub-dir1' / 'sub-dir2' / 'sub-dir3' / 'test.xlsx'
    # above code is only resolving file location, ignore 
    pd_Mst_df = pd.read_excel(xlspath)
    #print(pd_Mst_df) # for debug 
    print("... Writing Master DBF file ")
    df2dbf(pd_Mst_df, dbfpath) # dbf path is defined similar to pd_Mst path
    

    函数 df2dbg 使用 pysal 以 dbf 格式写入数据帧: 我对代码做了一些修改,检测长度行长和字符类型如下:

    import pandas as pd
    import pysal as ps
    import numpy as np
    
    # code from function df2dbf
    else:
        type2spec = {int: ('N', 20, 0),
                     np.int64: ('N', 20, 0),
                     float: ('N', 36, 15),
                     np.float64: ('N', 36, 15),
                     str: ('C', 200, 0)
                     }
        #types = [type(df[i].iloc[0]) for i in df.columns]
        types = [type('C') for i in range(0, len(df.columns))] #84)] #df.columns)] #range(0,84)] # i not required, to be removed
        specs = [type2spec[t] for t in types]
    db = ps.open(dbf_path, 'w')
    # code continues from function df2dbf
    

    Pandas 数据框不需要进一步修改,因为所有源数据在提交到 Excel 文件之前都已正确格式化。

    我会在 stackoverflow 上找到 pysal 和 df2dbf 的链接。

    【讨论】:

      【解决方案3】:

      查看 Python Pandas 库...

      要从 excel 中读取 Pandas 数据框中的数据,您可以使用 pandas.read_excel

      将日期读入 Pandas 数据框后,您可以对其进行操作,然后使用 pandas.DataFrame.to_sql 将其写入数据库

      See also this explanation for dealing with database io

      【讨论】:

      • 一些示例代码会比链接更有用。
      • 当然!你用的是什么 Python 数据库适配器?
      • 不适合我。您提供了可能有用的链接,但 Stackoverflow 的重点是提供答案,而不是指向其他地方的链接。所以请放一些你将如何使用pandas.read_excelpandas.DataFrame.to_sql的示例代码,然后有链接供参考和进一步研究。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      相关资源
      最近更新 更多