![](/img/trans.png)
[英]How to use zip function to associate column number with value of excel cell using openpyxl
[英]how to get column number by cell value in python using openpyxl
我對 openpyxl 和 python 完全陌生,我在這個問題上遇到了困難,我需要你的幫助。
JAN FEB MAR MAR YTD 2019 YTD
25 9 57 23 7
61 41 29 5 57
54 34 58 10 7
13 13 63 26 45
31 71 40 40 40
24 38 63 63 47
31 50 43 2 61
68 33 13 9 63
28 1 30 39 71
我有一個包含上述數據的excel報告。 我想搜索包含特定字符串(即 YTD)的單元格並獲取 YTD 列的列號。 我想使用列號來提取該列的數據。 我不想使用行和單元格引用,因為 excel 文件會定期更新,因此 d 列將始終移動。
def t_PM(ff_sheet1,start_row):
wb = openpyxl.load_workbook(filename='report') # open report
report_sheet1 = wb.get_sheet_by_name('sheet 1')
col = -1
for j, keyword in enumerate(report_sheet1.values(0)):
if keyword=='YTD':
col = j
break
ff_sheet1.cell(row=insert_col + start_row, column= header['YTD_OT'], value=report_sheet1.cell(row=i + 7, column=col).value)
但是,我收到一個“'generator' object is not callable”錯誤。 我怎樣才能解決這個問題?
你的問題是report_sheet1.values
是一個生成器,所以你不能用(0)
調用它。 我根據您的代碼假設您不想依賴“YTD”將出現在第一行中,因此您迭代所有單元格。 這樣做:
def find_YTD():
wb = openpyxl.load_workbook(filename='report') # open report
report_sheet1 = wb.get_sheet_by_name('sheet 1')
for col in report_sheet1.iter_cols(values_only=True):
for value in col:
if isinstance(value, str) and 'YTD' in value:
return col
如果我們假定你是這個數據將在第一行,簡單地做:
for cell in report_sheet1[1]:
if isinstance(value, str) and 'YTD' in cell.value:
return cell.column
openpyxl
使用“基於 1”的行索引閱讀文檔 - 訪問多個單元格
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.