簡體   English   中英

嘗試使用 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM