首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用openpyxl旋转excel图表的轴

使用openpyxl旋转excel图表的轴
EN

Stack Overflow用户
提问于 2016-10-20 13:50:10
回答 1查看 1.6K关注 0票数 1

我试着用Data.Drawing来处理Excel,输出的图片是OK.But,x_axis不够漂亮,我想旋转它,但在文档中没有找到解决方案。

下面是使用XlsxWriter:solution的解决方案。

我的代码是这样的:

代码语言:javascript
复制
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

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

代码语言:javascript
复制
from openpyxl.chart.text import RichText
from openpyxl.drawing.text import RichTextProperties
c5.x_axis.txPr = RichText(bodyPr=RichTextProperties(rot="-2700000"))

- Excel xml中的代码

代码语言:javascript
复制
<valAx>
            some codes here
    <txPr>
        <a:bodyPr rot="-1350000" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"/>

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

上面的代码会破坏文件,直到我将这些代码添加到文件中

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

发布于 2016-10-24 10:31:53

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

代码语言:javascript
复制
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_axis旋转-45度。

复制现有属性并设置其旋转也可能会更方便一些:

代码语言:javascript
复制
chart.x_axis.title = 'Date'
chart.x_axis.txPr = deepcopy(chart.x_axis.title.text.rich)
chart.x_axis.txPr.properties.rot = "-2700000"
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40146418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档