其他分享
首页 > 其他分享> > 使用xlwings的api.FormatConditions设置单元格条件格式

使用xlwings的api.FormatConditions设置单元格条件格式

作者:互联网

在使用xlwings操作excel时,需要设置单元格的条件格式,在百度搜索半天没找到解决方案。在xlwings官网也没找到方法,但官网帮助文档中range.api描述说range.api返回pywin32的对象,其实xlwings就是对pywin32操作excel的一个封装,所以我搜索pywin32使用FormatConditions的方法,资料也很少,通过各种实验最后成功实现功能。在此做个记录方便以后查看。

实现方法如下:

1.因为要用到pywin32,所以没装的先安装一下:pip install pywin32

2.在自己的.py文件导入pywin32库:import win32com

3.设置单元格条件格式,给C1单元格添加介于A1、B1之间的条件格式:

       formula1 = '=A1'

       formula2 = '=B1'

       sheet.range('C1').api.FormatConditions.Add(win32c.client.constants.xlCellValue, win32c.client.constants.xlBetween, formula1, formula2)

        sheet.range('C1').api.FormatConditions(sheet.range('C1').api.FormatConditions.Count).SetFirstPriority()

        sheet.range('C1').api.FormatConditions(1).Font.TintAndShade = 0

        sheet.range('C1').api.FormatConditions(1).Interior.PatternColorIndex = -4105

        sheet.range('C1').api.FormatConditions(1).Interior.Color = 65535

        win32c.client.constants.xlBetween就是介于条件用的参数,这个参数和FormatConditions.SetFirstPriority()下面的代码可以通过参考VBA来设置,方法就是用excel录制宏,录制设置条件格式,然后查看录制宏的代码,把里面设置条件格式代码拿来修改下就可以了。

标签:单元格,sheet,FormatConditions,xlwings,pywin32,range,api,C1
来源: https://blog.csdn.net/pingfanren022/article/details/120383187