使用OpenPyXL导入多个Excel文件

时间:2016-05-11 20:10:08

标签: python excel openpyxl

我正在尝试读取多个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')

谢谢!

1 个答案:

答案 0 :(得分:3)

我真的不懂你的代码。看起来太复杂了。在工作表之间复制时,您可能希望使用ws.rows

wb1 = load_workbook('master.xlsx')
ws2 = wb1.active

for f in files:
    wb2 = load_workbook(f)
    ws2 = wb2['Sheet1']
    for row in ws2.rows[1:]:
          ws1.append((cell.value for cell in row))