使用Openpyxl将工作表(数据+样式)从一个工作簿复制到另一个工作簿 [英] Copy a worksheet (data+style) from a workbook to another in Python using openpyxl

查看:21
本文介绍了使用Openpyxl将工作表(数据+样式)从一个工作簿复制到另一个工作簿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我在使用Openpyxl的Python中找到的所有解决方案都只允许复制数据,而不允许复制样式。由于Linux目标计算机没有安装MS Office,因此不能使用xlwing。

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)
还请注意,在文档中,您也不能在工作簿之间复制工作表。如果工作簿以只读或只写模式打开,则无法复制工作表。

这篇关于使用Openpyxl将工作表(数据+样式)从一个工作簿复制到另一个工作簿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆