尝试使用OPENPYXL将一系列单元格从一个工作簿复制到另一个工作簿

时间:2020-06-25 10:22:10

标签: python excel openpyxl

我对Python相当陌生,并且正在尝试将选定范围的单元格(例如A4:A66)从一本工作簿复制到另一本。 我设法取得了所需的范围,但是将其复制到另一个工作簿时遇到了麻烦。 代码如下:

import openpyxl as xl;

#Open source workbook
filename = r'C:\Users\FileDestination\SOURCE.xlsx'
wb1 = xl.load_workbook(filename)
ws1 = wb1.worksheets[0]

#Open destination workbook
filename1 = r'C:\Users\FileDestination\Destination.xlsx'
wb2 = xl.load_workbook(filename1)
ws2 = wb2.active

#Read the maximum number of columns and rows in source
mr = ws1.max_row
mc = ws1.max_column

#Copying source range values from source to destination
for r in ws1['B16':'B31']:
    for c in r:
        print(c.value) #Just to see the range selected
        ws2.cell(row = 1, column = 1).value = c.value #I don't believe this is correct as it doesn't work

wb2.save(str(filename1)) #Saving the new workbook

print("Range successfully copied to new Workbook")

这段代码的最后一部分使我感到困惑...我不确定应该如何复制范围,上面的代码只是复制了新工作簿第一行和列中范围的最后一行。 另外,我知道它正在拉动我想要的范围,只是不确定如何复制。

任何帮助将不胜感激,谢谢

1 个答案:

答案 0 :(得分:0)

看到这个

x = 1
#Copying source range values from source to destination
for r in ws1['B16':'B31']:
    for c in r:
        print(c.value) #Just to see the range selected
        ws2.cell(row = x, column = 1).value = c.value
        x += 1