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



我对Python相当陌生,正在尝试将选定的单元格范围(例如A4:A66(从一个工作簿复制到另一个工作簿。 我已经设法获取了我需要的范围,但在将其复制到另一个工作簿时遇到问题。 代码如下:

import openpyxl as xl;
#Open source workbook
filename = r'C:UsersFileDestinationSOURCE.xlsx'
wb1 = xl.load_workbook(filename)
ws1 = wb1.worksheets[0]
#Open destination workbook
filename1 = r'C:UsersFileDestinationDestination.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")

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

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

看到这个

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

相关内容

最新更新