我必须从不同的工作簿中复制数据并将其粘贴到主工作簿中。所有工作簿均位于以下文件夹中:C:\ Users \ f65651 \ data transfer。复制的数据应合并为一个,然后覆盖到主wkbk单元中。随后,更新后的工作簿中的数据也应在主wkbk中覆盖。
经过一些帮助,我已经能够将所有excel工作簿合并在一起
import openpyxl as xl
import os
path1 ='C:\\Users\\f65651\Rresult.xlsx' #Master workbook
wb1 = xl.load_workbook(filename=path1)
ws1 = wb1.worksheets[0]
#iterating over the workbooks
for filename in os.listdir(directory):
if filename.endswith(".xlsx"):
g= os.path.join(directory, filename)
f =xl.load_workbook(filename=g)
f1 = f.worksheets[0]
print (filename, f1)
for row in f1:
values=[cell.value for cell in row]
ws1.append(values)
wb1.save(path1)
print ('Process finished!')
但是,使用上面的代码,数据将附加到Master wkbk现有表格式下,而不是直接覆盖到单元格中
我已尝试解决此问题,但我不知道如何。我觉得我没有将工作簿复制到Master wkbk中。我也不想丢失母版纸中的格式。请帮忙!
为了更好地理解这个问题,我附上了我要实现的目标的摘要,数据1和2是工作库的示例,结果文件是主表。
答案 0 :(得分:0)
from openpyxl import load_workbook
import os
directory = "workbooks"
master = Workbook()
master_sheet = master.active
master_sheet.title = "master_sheet"
for filename in os.listdir(directory):
if filename.endswith(".xlsx"):
file_path = os.path.join(directory, filename)
sheet = load_workbook(file_path).active
# Read each column's value of each excel sheet starting from row 3
for index, row in enumerate(sheet.iter_rows()):
if (index <= 1):
for cell in row:
master_sheet[cell.coordinate].value = cell.value
else:
row_dict = {cell.coordinate[:1]:cell.value for cell in row}
master_sheet.append(row_dict)
master.save("sheet3.xlsx")