![](/img/trans.png)
[英]How to copy worksheet from one workbook to another one using openpyxl?
[英]Copy a worksheet (data+style) from a workbook to another in Python using openpyxl
我有大量 XLS 文件(超過 500 個),我只需要替換第一張。 需要是第一個工作表的數據+樣式(字體、背景、邊框、單元格 alignment 甚至圖像)的完美副本。
我在 Python 中使用 openpyxl 找到的所有解決方案只允許它復制數據,沒有樣式。 並且使用 xlwings 這不是一個選項,因為 Linux 目標機器沒有 MS Office。
import openpyxl as pyxl
import re
basereportworkbook = pyxl.load_workbook(filename="base_template.xlsx")
testreportworkbook = pyxl.load_workbook(filename="file1_to_correct.xlsx")
sheetbase = basereportworkbook.get_sheet_by_name("Coverpage")
sheetreport = basereportworkbook.get_sheet_by_name("Coverpage")
# Remove the 1st page from the file to correct
testreportworkbook.remove(testreportworkbook["Coverpage"])
testreportworkbook.create_sheet("Coverpage")
sheetreport = testreportworkbook.get_sheet_by_name("Coverpage")
# Copying the cell values from template excel file to destination excel file, one by one
mr = sheetbase.max_row
mc = sheetbase.max_column
for i in range (1, mr + 1):
for j in range (1, mc + 1):
# reading cell value from source excel file
c = sheetbase.cell(row = i, column = j)
# writing the read value to destination excel file
sheetreport.cell(row = i, column = j).value = c.value
# Save the XLS file in the disk
testreportworkbook.save(filename="output.xlsx")
到目前為止,這是我的代碼,它僅用於復制數據而無需格式化樣式。 謝謝!
當您使用c.value
時,您指定您只想復制該值而不是任何其他單元格屬性(格式等)。 您可以使用copy
來移動所有_style
格式,例如:
from copy import copy
sheetreport.cell(row = i, column = j).value = c.value
if cell.has_style:
sheetreport.cell(row = i, column = j)._style = copy(c._style)
……等等。
但是,如果您只想復制整個工作表,我可能只會復制整個工作簿,然后刪除所有其他工作表,而不是遍歷每個單元格。
shutil.copyfile('base_template.xlsx', 'file1_to_correct.xlsx')
testreportworkbook = pyxl.load_workbook(filename='file1_to_correct.xlsx')
for ws in testreportworkbook.worksheets[1:]:
testreportworkbook.remove_sheet(ws)
另請注意,來自文檔:“您也無法在工作簿之間復制工作表。如果工作簿以只讀或只寫模式打開,則無法復制工作表。”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.