【发布时间】:2021-04-27 13:44:52
【问题描述】:
这是这个问题How can I iterate through excel files sheets and insert formula in Python?的延续
我决定将它作为另一个问题放在新线程上。我有兴趣将公式复制到多个工作簿中各行的列中。我的代码在下面,问题出在 for 循环中。
import openpyxl
in_folder = r'C:\xxx' #Input folder
out_folder = r'C:\yyy' #Output folder
if not os.path.exists(out_folder):
os.makedirs(out_folder)
dir_list = os.listdir(in_folder)
print(dir_list)
for xlfile in dir_list:
if xlfile.endswith('.xlsx') or xlfile.endswith('.xls'):
str_file = xlfile
work_book = openpyxl.load_workbook(os.path.join(in_folder,str_file))
work_sheet = work_book['Sheet1']
for i, cellObj in enumerate(work_sheet['U'], 1): #The cell where the formula is to be inserted and iterated down to the last row
cellObj.value = '=Q2-T2' #Cells value. This is where I'm going wrong but I'm not sure of the best way to have '=Q3-T3' etc till the last row. For each iteration, Q2 and T2 will be incremented to Q3 and T3 till the last row in the dataset.
work_book.save(os.path.join(out_folder, xlfile)) #Write the excel sheet with formulae to another folder
当我在活动工作表中循环到最后时,如何增加公式中的行数?更多细节在代码旁边的 cmets 中。
【问题讨论】:
-
编辑原问题会更好。
标签: python excel pandas openpyxl