python + xlwings 操作Excel,复制粘贴保留格式

在使用python处理Excel时,需求是要保留Excel内的格式(例如字体,大小,背景颜色,函数公式....),试了其它几个库,都没达到效果,偶然发现了xlwings ,可以达到我所需要的效果。

import xlwings as xw
from xlwings.constants import PasteType

打开Excel文件

workbook = xw.Book('example.xlsx')

选择源工作表和范围

source_sheet = workbook.sheets['Sheet1']
source_range = source_sheet.range('A1:B10')

选择目标工作表和起始单元格

target_sheet = workbook.sheets['Sheet2']
target_cell = target_sheet.range('A1')

复制并粘贴数据(不保留格式)

source_range.api.Copy()
target_cell.api.PasteSpecial(Paste=PasteType.xlPasteValues)

复制并粘贴数据(保留格式)

source_range.api.Copy()
target_cell.api.PasteSpecial(Paste=PasteType.xlPasteAllUsingSourceTheme) # 或者 PasteType.xlPasteAllMergingConditionalFormats

保存并关闭工作簿

workbook.save()
workbook.close()

以上代码测试符合个人操作需求,代码来源于GPT,记录备用.

posted @ 2024-03-18 15:04  暮夜秋雨  阅读(1520)  评论(0)    收藏  举报