谢谢@Xiaofu,您在导出前关于图表激活的信息对我很有帮助,因为我花了将近一天的时间来为我的小 Python 项目寻找解决方案。干杯。
对于正在寻找 Python 脚本版本以将 Excel 图表导出为 GIF 或 PNG 格式的任何人,以下是对我有用的代码:
# Python function to export an Excel chart to a GIF image format
# Ref: https://stackoverflow.com/questions/11110752/export-charts-from-excel-as-images-using-python
def ChartExport(cwd, fileName):
app = win32.Dispatch('Excel.Application')
workbook_file_name = cwd + fileName
workbook = app.Workbooks.Open(Filename=workbook_file_name)
# WARNING: The following line will cause the script to discard any unsaved changes in your workbook
app.DisplayAlerts = False
i = 1 # There are multiple charts on the worksheet. So using a number suffix to add the output gif filename
for sheet in workbook.Worksheets:
for chartObject in sheet.ChartObjects():
#print('i = ', i, ' -- ', sheet.Name + ':' + chartObject.Name)
chartObject.Activate() # This line was added after finding exporting problem with 2nd and 3rd charts. Thanks Xiaofu Ref: https://stackoverflow.com/questions/15911536/excel-chart-export-not-working
chartObject.Chart.Export(cwd + '\\chart' + str(i) + '.gif') # Export chart to a gif file format
i += 1
workbook.Close(SaveChanges=False, Filename=workbook_file_name)
return