我正在尝试使用 openpyxl 在 Excel 中编辑图表。我正在编辑,因为我的工作在图表类型和数据方面存在差异,但我的公司使用特定的图表格式和字体。该代码确实适用于第一个图表,但如果我尝试编辑另一个图表,则会出现索引超出范围错误。
def graph_formatting(file, font_style = 'Times New Roman', fill_color = "000000"):
wb = opyxl.load_workbook(file)
allSheetNames = wb.sheetnames
ws = wb.active #renders it active
dechart = ws._charts[1] #the problematic code.
print(allSheetNames)
font_test = Font(typeface=font_style)
cp = CharacterProperties(latin=font_test, sz=1500)
dechart.x_axis.txPr = RichText(
p=[Paragraph(
pPr=ParagraphProperties(defRPr=cp),
endParaRPr=cp)
])
dechart.x_axis.graphicalProperties.line.solidFill = fill_color #changes the line color
dechart.y_axis.graphicalProperties.line.noFill = False #draws the y axis line
dechart.y_axis.majorGridlines = None #gets rid of gridline
dechart.y_axis.majorTickMark = 'out' #create tickmarks for x and y axis
dechart.x_axis.majorTickMark = 'out'
dechart.title ='' #deletes the chart title
#wb.save(path)
wb.save(file)
如果我设置
ws._charts[0]
,它会在第一个图表上工作。如果我设置 ws._charts[1]
,我会发现列表索引超出范围。我正在尝试编辑第二张图表,希望能编辑更多。
您想将代码更改为如下所示;
使用 for 循环遍历可用图表,请参阅下面对代码示例的更改;
使用
for dechart in ws._charts:
因此,“dechart”在第一个循环上分配为
ws._chart[0]
,然后在第二个循环上分配为 ws._chart[1]
,依此类推。此代码更改涵盖同一张纸上的图表。
您的代码还会获取可用工作表的列表,但不会对此执行任何操作,并且仅适用于活动工作表。
您可能对
wb.active
命令有一些误解;
ws = wb.active # renders it active
这并不会真正渲染任何活动的东西(除非您正在谈论工作表对象)。这会将工作表对象“ws”设置为上次保存时工作簿中最后一个“使用中”的工作表。因此,它可能是也可能不是带有图表的表格。
如果同一工作簿中的其他工作表上有图表,或者活动工作表不能保证是包含图表的工作表,您可能还需要循环遍历工作表。 IE。选择第一个工作表,处理该工作表中的图表,选择下一个工作表,依此类推。
如果这是所需的操作,则需要一个外部循环来执行此操作。
import openpyxl as opyxl
from openpyxl.chart.text import RichText
from openpyxl.drawing.text import CharacterProperties, Paragraph, ParagraphProperties, Font
def graph_formatting(file, font_style='Times New Roman', fill_color="000000"):
wb = opyxl.load_workbook(file)
allSheetNames = wb.sheetnames
print(allSheetNames)
ws = wb.active # renders it active
# dechart = ws._charts[1] # the problematic code.
dechart = None
### Loop through each chart in the list so 'dechart` is assigned to each chart available.
for dechart in ws._charts:
font_test = Font(typeface=font_style)
cp = CharacterProperties(latin=font_test, sz=1500)
dechart.x_axis.txPr = RichText(p=[Paragraph(pPr=ParagraphProperties(defRPr=cp), endParaRPr=cp)])
#
dechart.x_axis.graphicalProperties.line.solidFill = fill_color # changes the line color
dechart.y_axis.graphicalProperties.line.noFill = False # draws the y axis line
dechart.y_axis.majorGridlines = None # gets rid of gridline
dechart.y_axis.majorTickMark = 'out' # create tickmarks for x and y axis
dechart.x_axis.majorTickMark = 'out'
dechart.title = '' # deletes the chart title
# wb.save(path)
if dechart: # If there was a chart then save otherwise nothing changed
wb.save(file)
graph_formatting('chart.xlsx')