使用Openpyxl旋转EXCEL图表的轴 [英] Rotate the axis of an excel chart using openpyxl

查看:38
本文介绍了使用Openpyxl旋转EXCEL图表的轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

那里 我正在尝试使用Openpyxl来处理Excel数据。拉出图片并将其导出是可以的。但x_轴不够美观,我想旋转它,但在文档中找不到解决方案。

以下是使用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"

这篇关于使用Openpyxl旋转EXCEL图表的轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆