[英]Rotate the axis of an excel chart using openpyxl
在那里,我正在嘗試使用openpyxl來處理Excel Data.Drawing圖片並導出它們是正常的。但是x_axis還不夠,我想旋轉它但是沒有在doc中找到解決方案。
以下是使用XlsxWriter: 解決方案的解決方案 。
我的代碼是這樣的:
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_axis -45度。
制作現有屬性的副本並設置其旋轉可能更方便一些:
chart.x_axis.title = 'Date'
chart.x_axis.txPr = deepcopy(chart.x_axis.title.text.rich)
chart.x_axis.txPr.properties.rot = "-2700000"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.