如何以1 Python递增某些行
我似乎想不出增加ws2单元格值的方法。现在,当for循环遍历我的文件时,数据刚刚被写入ws2单元格。我是如何做到这一点的,而不是只向单元格ws2 A2写入,它每次递增1,然后它会下一次写入A3,与ws2 D2相同,每次递增1,然后它会下一次写入D3,以此类推如何以1 Python递增某些行,python,rows,openpyxl,increment,Python,Rows,Openpyxl,Increment,我似乎想不出增加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
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)
这对你有用吗
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
你需要做两件事:
ws2
中写入的行号。迭代文件列表时,可以使用enumerate()
,然后向这些索引添加偏移量
您可以使用
enumerate()
:
首先你需要一个计数器变量。使用
ws2.iter\u行(minu\u row=2,max\u row=…)
为什么不初始化i=2
这样你就不必每次都加2?你也可以,这只是个人习惯。我有一个问题,如果我不使用enumerate,它仍然可以正常工作,如果我使用Adrien KaczmarekI的选项,很抱歉,我不明白你的问题。您是否询问我的解决方案是否在不使用enumerate
的情况下有效?是的,是的。@Kristenl2784是的,有办法。编写一个循环,遍历所有行,检查ws['F'+int(row)]='0'并递增计数器。谢谢大家的帮助。所有这些选项都非常有效。我是python新手,所以看看有多少种不同的方法可以实现它总是很好的。
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)
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)