簡體   English   中英

Openpyxl - 將單元格范圍(帶公式)從工作簿復制到另一個

[英]Openpyxl - Copy range of cells(with formula) from a workbook to another

我正在嘗試將工作簿 1 和 append 中的特定行復制到工作簿 2 中的現有數據中。

將突出顯示的行從Workbook 1和 append 復制到Workbook 2下面的“March”

到目前為止,我成功復制並粘貼了范圍,但是有兩個問題:

1.細胞是移位的

2.百分比(公式)丟失,只留下數值。

在此處查看結果

import openpyxl as xl

source = r"C:\Users\Desktop\Test_project_20200401.xlsx"
wbs = xl.load_workbook(source)
wbs_sheet = wbs["P2"] #selecting the sheet

destination = r"C:\Users\Desktop\Try999.xlsx"
wbd = xl.load_workbook(destination)
wbd_sheet = wbd["A3"] #select the sheet

row_data = 0

for row in wbs_sheet.iter_rows():
    for cell in row:
        if cell.value == "Yes":
            row_data += cell.row

for row in wbs_sheet.iter_rows(min_row=row_data, min_col = 1, max_col=250, max_row = row_data+1):
    wbd_sheet.append((cell.value for cell in row))            


wbd.save(destination)

有誰知道我該如何解決這個問題? 任何反饋/解決方案都會有所幫助!

謝謝!

我認為min_col應該= 0

Range("A1").Formula (在 VBA 中)獲取公式。 Range("A1").Value(在 VBA 中)獲取值。

所以嘗試在 Python 中使用.formula

(感謝: 從單元格中獲取公式 - VBA ...如果可行)

只想在這里添加我自己的解決方案。

我所做的是遍歷列並應用“cell.number_format = '0%',它將您的單元格值轉換為百分比。

for col in ws.iter_cols(min_row=1, min_col=2, max_row=250, max_col=250):
    for cell in col:
        cell.number_format = '0%'

更多信息可以在這里找到: https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/styles/numbers.html

暫無
暫無

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

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