我想使用 openpyxl 设置面积图背景的透明度。我的图表代码是:
from openpyxl.drawing.fill import PatternFillProperties, ColorChoice
c2 = AreaChart()
c2.grouping = 'stacked'
c2.add_data(data, titles_from_data=True)
c2_s1 = c2.series[0]
fill = PatternFillProperties()
fill.background = ColorChoice(srgbClr="FFFFFF")
c2_s2.graphicalProperties.pattFill = fill
我尝试过使用rgba十六进制编码。
fill.background = ColorChoice(srgbClr="80FFFFFF")
我也尝试过使用
SystemColor
,但我找不到任何如何使用它的示例,并且我所做的每一次尝试都失败了
扩展颜色选择
from openpyxl.compat import unicode
from openpyxl.descriptors import Typed
from openpyxl.descriptors.serialisable import Serialisable
from openpyxl.descriptors.nested import NestedInteger
from openpyxl.xml.constants import DRAWING_NS
class MyRGBColor(Serialisable):
tagname = 'srgbClr'
namespace = DRAWING_NS
val = Typed(expected_type=unicode)
alpha = NestedInteger(allow_none=True)
__elements__ = ('alpha', )
def __init__(self, val, alpha=None):
self.val = val
self.alpha = alpha
class MyColorChoice(ColorChoice):
srgbClr = Typed(expected_type=MyRGBColor, allow_none=True)
..和
c2_s1.graphicalProperties.solidFill = MyColorChoice(
srgbClr=MyRGBColor('0000FF', alpha=50000))
我怀疑如果不修改 openpyxl 源代码,您想要做的事情目前是不可能的。请参阅“此拉取请求”以获取更多信息。
更新了 @Mosaic 的
openpyxl==3.1.2
实现并进行了一些调整:
from typing import Optional
from openpyxl.descriptors import Typed
from openpyxl.descriptors.serialisable import Serialisable
from openpyxl.descriptors.nested import NestedInteger
from openpyxl.xml.constants import DRAWING_NS
from openpyxl.drawing.colors import ColorChoice
class RGBAColor(Serialisable):
tagname = 'srgbClr'
namespace = DRAWING_NS
val = Typed(expected_type=str)
alpha = NestedInteger(allow_none=True)
__elements__ = ('alpha', )
def __init__(self, hex: str, alpha: Optional[float] = None):
if alpha != None and not (0 <= alpha <= 1):
raise ValueError('Alpha value must be between 0 and 1')
self.val = hex.replace('#', '')
if alpha: self.alpha = alpha * 10**5
class ExtendedColorChoice(ColorChoice):
srgbClr = Typed(expected_type=RGBAColor, allow_none=True)
用途:
from openpyxl.chart.series import Series
from openpyxl.chart.shapes import GraphicalProperties
series: Series = chart.series[0]
series.graphicalProperties = GraphicalProperties()
series.graphicalProperties.solidFill = ExtendedColorChoice(
srgbClr=RGBAColor('#F79D56', alpha=0.5)
)