使用openpyxl以这种方式操作Excel文件需要很多细节。首先,值得一提的是,xlsx文件包含每个单元格的两种表示形式—公式和公式的当前值。openpyxl可以返回其中一个,如果需要值,则应在打开文件时指定data_only=True。另外,当您更改单元格的公式时,openpyxl无法计算新值—只有Excel本身可以计算。因此,插入MATCH()工作表函数并不能解决问题。在
下面的代码可以满足您的需要,主要是用Python编写的。它使用“A1”引用样式,并进行一些计算以将列编号转换为列字母。如果超过了Z列,这就不能正常工作了。在这种情况下,您可能需要切换到对行和列的编号引用。还有一些关于here和{a2}的更多信息。但希望这能让你上路。在
注意:此代码假定您正在阅读名为'测试.xlsx,而“COGS”在“Sheet1”中的项目列表中!A2:A5'和在'Sheet1'中列出了年份!B1:E1'。在import openpyxl
def get_xlsx_region(xlsx_file, sheet, region):
""" Return a rectangular region from the specified file.
The data are returned as a list of rows, where each row contains a list
of cell values"""
# 'data_only=True' tells openpyxl to return values instead of formulas
# 'read_only=True' makes openpyxl much faster (fast enough that it
# doesn't hurt to open the file once for each region).
wb = openpyxl.load_workbook(xlsx_file, data_only=True, read_only=True)
reg = wb[sheet][region]
return [[cell.value for cell in row] for row in reg]
# cache the lists of years and items
# get the first (only) row of the 'B1:F1' region
years = get_xlsx_region('test.xlsx', 'Sheet1', 'B1:E1')[0]
# get the first (only) column of the 'A2:A6' region
items = [r[0] for r in get_xlsx_region('test.xlsx', 'Sheet1', 'A2:A5')]
def find_correct_cell(year, item):
# find the indexes for 'COGS' and
year_col = chr(ord('B') + years.index(year)) # only works in A:Z range
item_row = 2 + items.index(item)
cell_reference = year_col + str(item_row)
return cell_reference
print find_correct_cell(year=, item='COGS')
# C3