python - 使用openpyxl旋转Excel图表的轴

标签 python excel openpyxl

那里 我正在尝试使用openpyxl来处理Excel数据。将图片绘制出来并导出它们就可以了。但是x_axis不够漂亮,我想旋转它,但在文档中没有找到解决方案。

这是使用 XlsxWriter 的解决方案:solution .

我的代码是这样的:

from openpyxl import load_workbook
from openpyxl.chart import (
    ScatterChart,
    LineChart,
    Reference,
    Series,
    shapes,
    text,
    axis)
wb = load_workbook('text.xlsx')
ws = wb.active  
c5 = ScatterChart()
x = Reference(ws, min_col=1, min_row=2, max_row=ws.max_row)
for i in range(3,5):
    values = Reference(ws, min_col=i, min_row=1, max_row=ws.max_row)
series = Series(values, xvalues=x, title_from_data=True)
# series.marker.symbol = 'triangle'
c5.series.append(series)
c5.x_axis.number_format='yyyy/mm/dd'
c5.x_axis.title = 'Date'   

谢谢大家!

我的Python版本是3.5.2,openpyxl是2.4.0

----------------新代码旋转但使文件损坏并需要修复

from openpyxl.chart.text import RichText
from openpyxl.drawing.text import RichTextProperties
c5.x_axis.txPr = RichText(bodyPr=RichTextProperties(rot="-2700000"))

------------- Excel xml 中的代码

<valAx>
            some codes here
    <txPr>
        <a:bodyPr rot="-1350000" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"/>

    </txPr>
    <crossAx val="20"/>
</valAx>

上面的代码会破坏文件,直到我将它们添加到其中

<txPr>
    <a:bodyPr rot="-1350000" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"/>
    <a:p xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
        <a:pPr xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
            <a:defRPr xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"/>
        </a:pPr>
        <a:endParaRPr xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" lang="zh-CN"/>
    </a:p>
</txPr>

最佳答案

感谢@Charlie Clark 我终于得到答案 添加代码如下:

from openpyxl.chart.text import RichText
from openpyxl.drawing.text import  RichTextProperties,Paragraph,ParagraphProperties, CharacterProperties
c5.x_axis.txPr = RichText(bodyPr=RichTextProperties(anchor="ctr",anchorCtr="1",rot="-2700000",
           spcFirstLastPara="1",vertOverflow="ellipsis",wrap="square"),
        p=[Paragraph(pPr=ParagraphProperties(defRPr=CharacterProperties()), endParaRPr=CharacterProperties())])

有点复杂,但是可以从openpyxl文档中学习

txPr 类型为 RichText,由(bodyPr 和 p)组成,bodyPr 定义其属性,p 是一个序列,决定是否显示轴。

它可以将图表的x_轴旋转-45度。

制作现有属性的副本并设置其旋转可能会更方便:

chart.x_axis.title = 'Date'
chart.x_axis.txPr = deepcopy(chart.x_axis.title.text.rich)
chart.x_axis.txPr.properties.rot = "-2700000"

关于python - 使用openpyxl旋转Excel图表的轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40146418/

相关文章:

python - 如何在 Openpyxl 中找到最后一个非空白单元格?

python - 如果值不在 self._dict : TypeError: unhashable type: 'StyleProxy' in python

python - 音乐轨道数据库

python - 如何用 python re.sub 仅替换部分匹配项

excel - 如何将 ArrayLists 添加到 ArrayList 中?

使用非相邻单元格数组的excel公式

用于打印的 openpyxl 格式工作表?

Python:将 try 代码与 try 语句放在同一行有什么好处吗?

python - 无法在 linux 上安装 python 设置工具

excel - 运行大量 VBA 后出现打印预览问题