因為工作需要對excel做了系列的處理,對于其中的幾個功能實現(xiàn)頗費了一些精力饭寺,自己手動寫了一些function阻课。
合并單元格的split
首先獲得這張sheet中所有的合并單元格,再依次循環(huán)每一個艰匙,因為合并單元格都是返回其第一個行列的值限煞,所以只需要返回該值即可。
def unmergedValue(rowx, colx, thesheet):
'''
Split merged cells.
'''
for crange in thesheet.merged_cells:
rlo, rhi, clo, chi = crange
if rowx in range(rlo, rhi):
if colx in range(clo, chi):
return thesheet.cell_value(rlo, clo)
#if you reached this point, it's not in any merged cells
return thesheet.cell_value(rowx, colx)
表頭拆分
這里用到了字典占位的思想员凝,以及利用了yield閱后即焚的效果
首先要有所有的表頭list署驻,在這個list中的元素,即被分類
def split_tab_title(header, utitle):
'''
Split the separate tables' header from the title row of an excel sheet.
'''
tmp_dict = {i: None for i in header}
tmp_tab = {}
ntitle = [i.lower().replace(' ', '') for i in utitle]
unamelist = [i.lower().replace(' ', '') for i in header]
for idx, name in enumerate(ntitle):
if name in unamelist:
pos = unamelist.index(name)
element = header[pos]
#try:
if not tmp_dict[element]:
tmp_dict[element] = element
tmp_tab[element] = idx
else:
yield tmp_tab
tmp_dict = {i: None for i in header}
tmp_tab = {}
tmp_dict[element] = element
tmp_tab[element] = idx
#except KeyError:
#print(element + ' is not header type')
yield tmp_tab
確定好了表頭的index之后健霹,再逐一讀行旺上,獲得其對應(yīng)的元素
def get_tab_value(values, record):
'''
Get each line info for each table value.
'''
record_dict = {}
for tab in record:
for name, idx in tab.items():
record_dict[name] = values[idx]
yield record_dict
此處代碼內(nèi)部的dict只要更新了,key不變糖埋,但value會改變宣吱,只做循環(huán)的時候看不出來,但是瞳别,如果轉(zhuǎn)成list征候,就會發(fā)現(xiàn)只能迭代最后一次的value。故代碼需要修改祟敛,如下才是正確的代碼疤坝。
def get_tab_value(values, record):
'''
Get each line info for each table value.
'''
record_dict = {}
for tab in record:
if not record_dict:
for name, idx in tab.items():
record_dict[name] = values[idx]
else:
yield record_dict
record_dict = {}
for name, idx in tab.items():
record_dict[name] = values[idx]
yield record_dict
此處有個大坑,就是yield是只能迭代一次的馆铁,下次再使用它已經(jīng)空了,所以要么用list把record存好跑揉,要么每次迭代這個record。
records = list(split_tab_title(header, utitle)) ####can be iterable more than once
for row_index in range(title_row_index + 1, sheet.nrows):
tab_record = get_tab_value(values, records)
或者埠巨,每次循環(huán)都生成generator历谍,其實也不占內(nèi)存
for row_index in range(title_row_index + 1, sheet.nrows):
records = split_tab(header,mytitle) ###generator only use once
tab_record = get_tab_value(values, records)