我试图读取多个Excel文件,并将每个文件中的数据附加到一个主文件中。每个文件都有相同的头文件(所以我可以跳过导入初始文件后的第一行)。
我对Python和OpenPyXL模块都很陌生。我能够导入第一个工作簿没有问题。当我需要打开后续文件并复制数据以粘贴到原始工作表中时,问题就出现了。
以下是我目前为止的代码:
# Creating blank workbook
from openpyxl import Workbook
wb = Workbook()
# grab active worksheet
ws = wb.active
# Read in excel data
from openpyxl import load_workbook
wb = load_workbook('first_file.xlsx') #explicitly loading workbook, will automate later
# grab active worksheet in current workbook
ws = wb.active
#get max columns and rows
sheet = wb.get_sheet_by_name('Sheet1')
print ("Rows: ", sheet.max_row) # for debugging purposes
print ("Columns: ", sheet.max_column) # for debugging purposes
last_data_point = ws.cell(row = sheet.max_row, column = sheet.max_column).coordinate
print ("Last data point in current worksheet:", last_data_point) #for debugging purposes
#import next file and add to master
append_point = ws.cell(row = sheet.max_row + 1, column = 1).coordinate
print ("Start new data at:", append_point)
wb = load_workbook('second_file.xlsx')
sheet2 = wb.get_sheet_by_name('Sheet1')
start = ws.cell(coordinate='A2').coordinate
print("New data start: ", start)
end = ws.cell(row = sheet2.max_row, column = sheet2.max_column).coordinate
print ("New data end: ", end)
# write a value to selected cell
#sheet[append_point] = 311
#print (ws.cell(append_point).value)
#save file
wb.save('master_file.xlsx')
谢谢!
2条答案
按热度按时间jogvjijk1#
我不太懂你的代码。看起来太复杂了。在工作表之间复制时,您可能希望使用
ws.rows
。tv6aics12#
你可以用途:wb = load_workbook('master.xlsx')使用此函数,您可以通过简单地创建一个变量来访问多个工作簿,例如wb2 = load_workbook(“master2.xlsx”)。现在访问工作簿中的工作表:wd = wb[“Sheetname”]。现在你可以编辑它了。