Copy a worksheet (data+style) from a workbook to another in Python using openpyxl(使用Openpyxl将工作表(数据+样式)从一个工作簿复制到另一个工作簿)
本文介绍了使用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将工作表(数据+样式)从一个工作簿复制到另一个工作簿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用Openpyxl将工作表(数据+样式)从一个工作簿复制到另一个工作簿


基础教程推荐
猜你喜欢
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01