【发布时间】: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