[英]Transfer data from excel worksheet (openpyxl) to database table (dbf)
我有一個簡單的問題,即讀取Excel工作表,將包含約83列的每一行都視為唯一的數據庫記錄,將其添加到本地數據記錄中,最后追加並寫入DBF文件中。
我可以從excel中提取所有值並將其添加到列表中。 但是該列表的語法不正確,我不知道如何准備/將列表轉換為數據庫記錄。 我正在使用Openpyxl,dbf和python 3.7。
目前,我僅測試並嘗試准備第3行的數據(因此min_max行= 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'>
更改
tbl_tst.append(datum)
至
tbl_tst.append(tuple(datum))
這樣就可以消除該錯誤。 只要您所有的單元格數據都具有適當的類型,那么附加項就應該起作用。
謝謝您的回答,自昨晚以來,我嘗試了不同的解決方案,並進行了一些討論。
一種適用於我的解決方案如下:確保我使用的工作表數據是所有字符串/文本,並將所有空條目轉換為字符串類型並輸入空字符串。 因此,以下代碼可以完成此任務:
#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。
導入數據幀並轉換為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
熊貓數據框不需要進一步修改,因為所有源數據在提交給excel文件之前都已正確格式化。
一旦在stackoverflow上找到pysal和df2dbf,我將提供其鏈接。
查看Python Pandas庫...
要從excel讀取Pandas數據幀中的數據,可以使用pandas.read_excel
將日期讀入Pandas數據框后,您可以對其進行操作,然后再使用pandas.DataFrame.to_sql將其寫入數據庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.