尝试使用 OPENPYXL 将一系列单元格从一个工作簿复制到另一个工作簿
Trying to copy a range of cells from one workbook to another using 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")
这段代码的最后一部分让我感到困惑...我不确定我应该如何复制范围,上面的代码只是复制新工作簿第一行和第一列范围内的最后一行。
另外,我知道它正在拉动我想要的范围,只是不知道如何复制。
非常感谢任何帮助,谢谢
看到这个
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
我是 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")
这段代码的最后一部分让我感到困惑...我不确定我应该如何复制范围,上面的代码只是复制新工作簿第一行和第一列范围内的最后一行。 另外,我知道它正在拉动我想要的范围,只是不知道如何复制。
非常感谢任何帮助,谢谢
看到这个
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