【问题标题】:How can I loop through and increment the rows in an excel workbook formula in Python?如何在 Python 中循环并增加 Excel 工作簿公式中的行?
【发布时间】: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


【解决方案1】:

也许你可以尝试格式化字符串?

...
    row_count = 2
    for i, cellObj in enumerate(work_sheet['U'], 1):
        cellObj.value = f'=Q{row_count}-T{row_count}'
        work_book.save(os.path.join(out_folder, xlfile))
        row_count += 1

【讨论】:

  • 谢谢@Jasurbek。上面对每个文档中的行进行计数,并根据计数开始插入公式。例如,如果 1001.xlsx 有 6 行,那么它将在所有行中插入 Q6-T6。似乎与for 循环有关。
  • 我猜你的问题已经“改变”了?所以,您需要做的就是检测行数,然后对所有行使用 f'=Q{rc}-T{rc}'?然后this 问题答案“如何获取行数?”,然后您可以将它用于您的代码。
猜你喜欢
  • 1970-01-01
  • 2016-07-13
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多