问题描述
使用xlwings
修改边框颜色时,需要使用HEX颜色(16进制),研究发现该值对应Microsoft的RGB函数
实际上,调用from xlwings.utils import rgb_to_int
即可
代码
def rgb2hex(rgbcolor, tohex=False):
'''RGB转HEX
:param rgbcolor: RGB颜色元组,Tuple[int, int, int]
:param tohex: 是否转十六进制字符串,默认不转
:return: int or str
>>> rgb2hex((255, 255, 255))
16777215
>>> rgb2hex((255, 255, 255), tohex=True)
'0xffffff'
'''
r, g, b = rgbcolor
result = (r << 16) + (g << 8) + b
return hex(result) if tohex else result
def hex2rgb(hexcolor):
'''HEX转RGB
:param hexcolor: int or str
:return: Tuple[int, int, int]
>>> hex2rgb(16777215)
(255, 255, 255)
>>> hex2rgb('0xffffff')
(255, 255, 255)
'''
hexcolor = int(hexcolor, base=16) if isinstance(hexcolor, str) else hexcolor
rgb = ((hexcolor >> 16) & 0xff, (hexcolor >> 8) & 0xff, hexcolor & 0xff)
return rgb
VBA的RGB函数
对应Microsoft 颜色常量,适用于xlwings
的边框颜色等
公式如下:
Hex = R + G × 256 + B × 65536 \text{Hex}=\text{R}+\text{G}\times 256+\text{B}\times 65536 Hex=R+G×256+B×65536
实际上就是把R和B的权重换过来
def rgb2hex_VBA(rgbcolor, tohex=False):
'''RGB转HEX
:param rgbcolor: RGB颜色元组,Tuple[int, int, int]
:param tohex: 是否转十六进制字符串,默认不转
:return: int or str
>>> rgb2hex_VBA((0, 0, 0)) # 黑色
0
>>> rgb2hex_VBA((255, 0, 0)) # 红色
255
>>> rgb2hex_VBA((0, 255, 0)) # 绿色
65280
>>> rgb2hex_VBA((255, 255, 0)) # 黄色
65535
>>> rgb2hex_VBA((0, 0, 255)) # 蓝色
16711680
>>> rgb2hex_VBA((255, 0, 255)) # 洋红
16711935
>>> rgb2hex_VBA((0, 255, 255)) # 蓝绿
16776960
>>> rgb2hex_VBA((255, 255, 255)) # 白色
16777215
>>> rgb2hex_VBA((255, 255, 255), tohex=True)
'0xffffff'
'''
r, g, b = rgbcolor
result = r + (g << 8) + (b << 16)
return hex(result) if tohex else result
def hex2rgb_VBA(hexcolor):
'''HEX转RGB
:param hexcolor: int or str
:return: Tuple[int, int, int]
>>> hex2rgb_VBA(16777215)
(255, 255, 255)
>>> hex2rgb_VBA('0x0')
(0, 0, 0)
>>> hex2rgb_VBA('0xff00ff')
(255, 0, 255)
>>> hex2rgb_VBA('0xffffff')
(255, 255, 255)
'''
hexcolor = int(hexcolor, base=16) if isinstance(hexcolor, str) else hexcolor
rgb = (hexcolor & 0xff, (hexcolor >> 8) & 0xff, (hexcolor >> 16) & 0xff)
return rgb
常用颜色
color = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple'] # 红橙黄绿青蓝紫
color = {'red': '#FF0000', 'orange': '#FFA500', 'yellow': '#FFFF00', 'green': '#008000', 'cyan': '#00FFFF', 'blue': '#0000FF', 'purple': '#800080'} # 红橙黄绿青蓝紫