我们编写了一些代码,以将Powerpoint演示文稿中的图表数据更新为现有图表。为了更新图表数据,我们调用方法“ .SetSourceData(Source =)”。 但是,通过说:
'pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147467259), None)'
需要尽快解决该问题。
输入文件链接:https://www.sendspace.com/file/a1m5zx
import win32com.client
import pythoncom
import traceback
input_file = "C:/input.pptx"
output = "C:/output.pptx"
try:
pythoncom.CoInitialize()
slide_dict = {1: {'Chart 1': 'CHARTTAG_1062'}}
application = win32com.client.Dispatch("PowerPoint.Application")
excel = win32com.client.Dispatch("Excel.Application")
presentation = application.Presentations.Open(input_file, ReadOnly=0, Untitled=0, WithWindow=1)
e_workbook = None
for idx, Slide in enumerate(presentation.Slides):
if idx == 0:
continue
else:
print("slide_dict", slide_dict)
for Shape in Slide.Shapes:
for each in slide_dict[idx]:
if each == Shape.Name:
try:
chart = Shape.Chart
chartdata = chart.ChartData
chartdata.Activate()
e_workbook = chartdata.Workbook
chart.ChartData.Workbook.Application.Visible = True
e_workbook.Worksheets[0].Select()
e_worksheet = e_workbook.ActiveSheet
xlUp = -4162
lastrow = e_worksheet.Cells(e_worksheet.Rows.Count, "A").End(xlUp).Row + 1
try:
e_worksheet.Range("A1:Z" + str(lastrow)).Delete()
except Exception as e:
print("Error : " + str(e))
traceback.print_exc()
count = 2
chart_header = [' # Data 1 ', ' # Data2 ']
chart_data = [
[
"Category 1",
28.6404,
17.9532
],
[
"Category 2",
57.5819,
27.1754
],
[
"Category 3",
4.4474,
2.4474
]
]
for each_header in chart_header:
e_worksheet.Range(str(chr(65)) + str(count)).Value = each_header
count = count + 1
temp_count = 1
for each_row in range(0, len(chart_data)):
for each_col in range(0, len(chart_data[each_row])):
e_worksheet.Range(str(chr(65 + temp_count)) + str(each_col + 1)).Value = \
chart_data[each_row][each_col]
temp_count = temp_count + 1
Slide.Shapes(1).Chart.SetSourceData(Source=e_worksheet.Range("$A$1:$D$3"))
e_workbook.Close(SaveChanges=1)
print("Chart data updated. Please check the output file")
chart.Refresh()
except Exception as e:
print("ERROR <Inner Try Block>: " + str(e))
traceback.print_exc()
presentation.SaveAs(output)
application.Quit()
except Exception as e:
print("ERROR : " + str(e))
traceback.print_exc()
当我调用chart.SetSourceData方法时出现以下错误
pywintypes.com_error:(-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147467259), None)