python - 使用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")
到目前为止,这是我的代码,它仅用于复制数据而无需格式化样式。谢谢!
解决方案
当您使用 时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)
另请注意,来自文档:“您也无法在工作簿之间复制工作表。如果工作簿以只读或只写模式打开,则无法复制工作表。”
推荐阅读
- android - 数据成功从数据库中检索,但无法通过适配器类
- three.js - 运行两个版本的three.js
- c# - Richtextbox:在多行文本中查找多行字符串
- java - 远程连接的 mysql 服务器的数据库 URL 到底是什么?
- c# - 获取包的当前版本
- vb.net - 计算数据网格视图上的所有行,在 Vb.net 中不重复
- php - PHP array_diff_key() 为空但不应该
- raspberry-pi - 确定在 Pi Zero W (armv6) 上导致“非法指令”的库,并修复构建
- python - 使用一维数组的 Numpy 计算对数损失
- react-native - 为 RN 实现 kurento 客户端