在不删除 headers 的情况下使用公式填充列
Populating Columns with Formulas without erasing the headers
我在 xlsx 文件中有 headers 的数据,我正在使用 openpyxl 填充电子表格中的列,到目前为止一切正常,除了 headers 列被公式替换当我 运行 我的代码时,就是这个:
import openpyxl
#Opening a Workbook
wb = openpyxl.load_workbook('file.xlsx')
#Working with an specific sheet.
Sheet = wb.get_sheet_by_name('Data')
#Getting the max amount of rows in a given sheet.
row_count = Sheet.max_row
#GEO_CODE home_county
for i, cellObj in enumerate(Sheet['T'], 1):
cellObj.value = '=A{0}'.format(i)
#Total_Count
for i, cellObj in enumerate(Sheet['U'], 1):
cellObj.value = '=SUMIF($A:$A, T{0},$D:$D)'.format(i, row_count)
wb.save('file.xlsx')
如果我想从第二行而不是第一行开始复制公式,我应该对我的代码做哪些更改?
感谢您的宝贵时间!
Question: I want to start copying formulas on the second row and not at the first one
Sheet['T']
returns tuple
个 Cell
个对象。
>>> (<Cell Data.T1>, <Cell Data.T2>, <Cell Data.T3>,...)
从第二行开始,跳过第一个Cell
对象,改为:
for i, cellObj in enumerate(Sheet['T'][1:], 2):
Note: A tuple
is 0-based, a openpyxl.Worksheet
is 1-based!
因此,您必须从索引 1 到末尾执行以下操作:[1:]
并从第 2 行开始获取行,执行 enumerate(..., 2)
.
我在 xlsx 文件中有 headers 的数据,我正在使用 openpyxl 填充电子表格中的列,到目前为止一切正常,除了 headers 列被公式替换当我 运行 我的代码时,就是这个:
import openpyxl
#Opening a Workbook
wb = openpyxl.load_workbook('file.xlsx')
#Working with an specific sheet.
Sheet = wb.get_sheet_by_name('Data')
#Getting the max amount of rows in a given sheet.
row_count = Sheet.max_row
#GEO_CODE home_county
for i, cellObj in enumerate(Sheet['T'], 1):
cellObj.value = '=A{0}'.format(i)
#Total_Count
for i, cellObj in enumerate(Sheet['U'], 1):
cellObj.value = '=SUMIF($A:$A, T{0},$D:$D)'.format(i, row_count)
wb.save('file.xlsx')
如果我想从第二行而不是第一行开始复制公式,我应该对我的代码做哪些更改?
感谢您的宝贵时间!
Question: I want to start copying formulas on the second row and not at the first one
Sheet['T']
returns tuple
个 Cell
个对象。
>>> (<Cell Data.T1>, <Cell Data.T2>, <Cell Data.T3>,...)
从第二行开始,跳过第一个Cell
对象,改为:
for i, cellObj in enumerate(Sheet['T'][1:], 2):
Note: A
tuple
is 0-based, aopenpyxl.Worksheet
is 1-based!
因此,您必须从索引 1 到末尾执行以下操作:[1:]
并从第 2 行开始获取行,执行 enumerate(..., 2)
.