如何用Python(openpyxl等)跨工作簿复制单元格内多色字体格式
解决OpenPyXL复制单元格内多色字体的问题
你的问题出在:普通的cell.value赋值和全局字体复制无法处理单元格内的富文本格式。当单元格存在部分文字变色的情况时,OpenPyXL会将单元格内容存储为RichText对象,而非普通字符串,每个文字片段对应独立的字体样式。
以下是可行的解决方案:
核心代码实现
from openpyxl import load_workbook from openpyxl.utils.cell import RichText source_path = "D:\\Python Projects\\Testing Copy Color Font\\Test 1.xlsx" target_path = "D:\\Python Projects\\Testing Paste Color Font\\Test 2.xlsx" # 加载工作簿,保留富文本需确保data_only=False(默认值,可显式声明) source_wb = load_workbook(source_path, data_only=False) target_wb = load_workbook(target_path) source_sheet = source_wb.active target_sheet = target_wb.active source_cell = source_sheet['A1'] target_cell = target_sheet['A1'] # 处理富文本内容 if isinstance(source_cell.value, RichText): # 直接赋值RichText对象,完整保留各片段的字体样式 target_cell.value = source_cell.value else: # 普通文本场景按原逻辑处理 target_cell.value = source_cell.value target_cell.font = source_cell.font # 可选:复制其他单元格格式(对齐、填充、边框等) if source_cell.alignment: target_cell.alignment = source_cell.alignment if source_cell.fill: target_cell.fill = source_cell.fill if source_cell.border: target_cell.border = source_cell.border target_wb.save(target_path)
关键说明
- RichText对象:当单元格内有多色字体或局部格式时,
source_cell.value会是RichText类型,内部包含多个TextBlock实例,每个实例对应一段文字和专属的Font样式,直接赋值即可完整保留局部格式。 - data_only参数:加载工作簿时不要设置
data_only=True,否则会丢失富文本结构,仅提取纯文本内容。 - 额外格式复制:如果需要对齐、边框等全局单元格格式,可按需复制对应属性,与富文本复制逻辑不冲突。
验证效果
运行上述代码后,目标单元格A1的“Hello”会保持黑色,“World”保持红色,完全复刻源单元格的富文本格式。
内容的提问来源于stack exchange,提问作者Strider
相关产品推荐
相关产品推荐

