我似乎无法找到增加 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
中写入的行号.您可以使用 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 - 如何将某些行增加 1 个 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62918777/