如何改进这个脚本。在 openpyxl 中将一列除以 3

How to improve this script. Dividing a column by 3 in openpyxl

正在寻找一种方法来简化列的划分。我可以使用循环吗?

from openpyxl import load_workbook

xfile = load_workbook('camdatatest.xlsx')

sheet =xfile.get_sheet_by_name('Sheet1')

sheet['D2'] = '=C2/3' # Want to divide all values in Column C with the new value in D.
sheet['D3'] = '=C4/3'
sheet['D4'] = '=C5/3'
sheet['D5'] = '=C6/3'
sheet['D6'] = '=C7/3'
sheet['D7'] = '=C8/3'
sheet['D8'] = '=C9/3'
sheet['D9'] = '=C10/3'




xfile.save("camdatatestoutput.xlsx")

这只是其中一种可能性。

for i in range(2,11):
    sheet['D{}'.format(i)] = '=C{}/3'.format(i)

注意 range 的工作方式,如果你想包含数字 10,你需要确保传入 11。