【问题标题】:How to increment certain rows by 1 Python如何将某些行增加 1 Python
【发布时间】:2020-11-05 04:22:51
【问题描述】:

我似乎无法找到增加 ws2 单元格值的方法。现在,当 for 循环遍历我的文件时,数据刚刚被写入 ws2 单元格。我是如何做到的,而不是只写入单元格 ws2 A2,它每次递增 1,然后接下来写入 A3,同样,对于 ws2 D2,每次递增 1,然后接下来写入 D3 等等。

import openpyxl as xl; 
import os
   
input_dir = 'C:\\work\\comparison\\NMN'
template = 'C:\\work\\comparison\\template.xlsx'
newFile = 'NNM_Comparison.xlsx'
  
  
  
  
files = [file for file in os.listdir(input_dir)
         if os.path.isfile(file) and file.endswith(".xlsx")]
  
for file in files:
    input_file =  os.path.join(input_dir, file)
    wb1=xl.load_workbook(input_file)
    ws=wb1.worksheets[0]

      
    wb2 = xl.load_workbook(template) 
    ws2 = wb2.worksheets[0] 
    ws2['A2']=ws['A1']
    ws2['D2']=ws['B4']
    ws2['E2']=ws['D4']

      
      
    output_file = (newFile)
    wb2.save(output_file)

【问题讨论】:

  • 首先你需要一个计数器变量。
  • 使用ws2.iter_rows(min_row=2, max_row=…)

标签: python rows openpyxl increment


【解决方案1】:

这对你有用吗?

i = 0
for file in files:
    input_file =  os.path.join(input_dir, file)
    wb1=xl.load_workbook(input_file)
    ws=wb1.worksheets[0]

      
    wb2 = xl.load_workbook(template) 
    ws2 = wb2.worksheets[0] 
    ws2[f'A{i+2}']=ws['A1']
    ws2[f'D{i+2}']=ws['B4']
    ws2[f'E{i+2}']=ws['D4']
    
    i += 1

【讨论】:

  • 为什么不直接初始化i=2 这样就不用每次都加2了?
  • 你也可以,只是个人习惯。
  • 我确实有一个问题,如果我不使用枚举,如果我使用 Adrien Kaczmarek 的选项,它仍然可以正常工作
  • 对不起,我不明白你的问题。您是否问过我的解决方案是否可以在不使用 enumerate 的情况下工作?是的,确实如此。
  • @Kristenl2784 是的,有办法。编写一个循环遍历所有行,检查是否ws['F' + int(row)] == '0' 并增加一个计数器。
【解决方案2】:

你需要做的两件事:

  1. 只打开一次模板。否则,每次循环时,您都是从原始模板开始,而不是组合每次迭代的结果。

  2. 使用计数器变量更改您在ws2 中写入的行号。您可以在遍历文件列表时使用enumerate(),然后为这些索引添加偏移量。

wb2 = xl.load_workbook(template) 
ws2 = wb2.worksheets[0] 

for i, file in enumerate(files):
    input_file =  os.path.join(input_dir, file)
    wb1=xl.load_workbook(input_file)
    ws=wb1.worksheets[0]

    row = str(i + 2)
      
    ws2['A' + row]=ws['A1']
    ws2['D' + row]=ws['B4']
    ws2['E' + row]=ws['D4']
      
output_file = (newFile)
wb2.save(output_file)

【讨论】:

  • 感谢大家的帮助。所有这些选项都很完美。我是 python 新手,所以很高兴看到可以实现多少种不同的方法。
【解决方案3】:

你可以使用enumerate():

wb2 = xl.load_workbook(template) 
ws2 = wb2.worksheets[0] 

for i, file in enumerate(files):
    input_file =  os.path.join(input_dir, file)
    wb1=xl.load_workbook(input_file)
    ws=wb1.worksheets[0]
      
    ws2['A' + str(i+2)]=ws['A1']
    ws2['D' + str(i+2)]=ws['B4']
    ws2['E' + str(i+2)]=ws['D4']      
      
    output_file = (newFile)
    wb2.save(output_file)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多