首页 > 解决方案 > 使用openpyxl将工作表(数据+样式)从工作簿复制到Python中的另一个

问题描述

我有大量 XLS 文件(超过 500 个),我只需要替换第一张。需要是第一个工作表的数据+样式(字体、背景、边框、单元格对齐甚至图像)的完美副本。

我在 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")

到目前为止,这是我的代码,它仅用于复制数据而无需格式化样式。谢谢!

标签: pythonexcelopenpyxlworksheet

解决方案


当您使用 时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)

另请注意,来自文档:“您也无法在工作簿之间复制工作表。如果工作簿以只读或只写模式打开,则无法复制工作表。”


推荐阅读