我已经被这个问题困扰了几个小时,所以我想我可以问问专家。我的任务是构建一个多步骤程序,该程序采用一个大型 Excel 文件的选项卡,这些选项卡根据唯一的单元格值进行更新,然后将其中一些选项卡导入到一个唯一的 ppt 中,然后将其保存到一个文件夹和该文件夹中随着程序循环遍历多个值,比值会变大,从而继续更新 Excel 文件。我最初使用 vba,但发现 excel 中的 vba 不允许我更新 powerpoint 中的链接,只有 excel 链接才有效。
简而言之,下面的代码从我的 Looper 文件中获取一个值,将其输入到 excel 中,然后更新链接到这些选项卡的 ppt 幻灯片。我的解决方案有效,但是当我打开文件时,我必须单击“不更新链接”,否则它将恢复到 Excel 文件上显示的任何选项卡。
我的问题是我不知道如何在保存之前断开PowerPoint中Excel文件的链接。我尝试了几个功能,但似乎都不起作用
如果有人有使用 win32 从 powerpoint 断开外部链接到 excel 的经验,我将非常感谢您的帮助。
------下面是我的代码-----
def fun_times():
# Set the path to the existing PowerPoint file
existing_ppt_path = r"C:/Users/dtalbot2/Desktop/x.pptm"
# Create PowerPoint application
ppt_app = win32com.client.Dispatch("PowerPoint.Application")
ppt_app.Visible = True # Uncomment this line if you want PowerPoint to be visible
# Open the existing PowerPoint presentation
ppt_pres = ppt_app.Presentations.Open(existing_ppt_path)
# Get the Excel application
excel_app = win32com.client.Dispatch("Excel.Application")
# Set paths and filenames
looper_path = r"C:/Users/dtalbot2/Desktop/Looper1.xlsx"
b_p_path = r"C:/Users/dtalbot2/Desktop/z.xlsm"
for i in range(1, 181):
# Activate Looper workbook
base_wb = excel_app.Workbooks.Open(looper_path)
base_wb.Activate()
# Set value in Looper worksheet
base_wb.Worksheets("Looper").Range("E1").Value = i
retailer_name = base_wb.Worksheets("Looper").Range("F1").Value
retailer_code = base_wb.Worksheets("Looper").Range("G1").Value
this_file_name = r"C:\Users\dtalbot2\Documents\BP\\" + str(retailer_name)
# Activate B_P workbook
target_wb = excel_app.Workbooks.Open(b_p_path)
target_wb.Activate()
# Set value in B_P worksheet
target_wb.Worksheets("BP Cover").Range("AF8").Value = retailer_code
ppt_pres.UpdateLinks()
# Save the PowerPoint presentation with the specified filename
ppt_pres.SaveAs(this_file_name + ".pptx") # You can change the extension if needed
# Close workbooks
base_wb.Close(False)
target_wb.Close(False)
# Close PowerPoint presentation
ppt_pres.Close()
# Close PowerPoint application
ppt_app.Quit()
if __name__ == "__main__":
fun_times()
我尝试在 fun_times() 函数上方定义一个中断链接函数,然后将其包含在 fun times 函数中,但这不起作用。相反,程序基本上陷入了中断链接功能。没用。
要使用 win32com.client 断开 PowerPoint 演示文稿中 Excel 文件的链接,您可以迭代 PowerPoint 演示文稿每张幻灯片中的形状。对于每个形状,如果它链接到 Excel 文件,您可以将其替换为静态副本。此方法有效地破坏了链接,因为数据将不再从 Excel 文件更新。所以尝试修改你的代码,如下所示:
import win32com.client
def break_links(presentation):
for slide in presentation.Slides:
for shape in slide.Shapes:
if shape.Type == win32com.client.constants.msoLinkedOLEObject:
# This checks if the shape is a linked OLE object (like an Excel link)
shape.LinkFormat.BreakLink()
def fun_times():
# Existing code ...
# Open the existing PowerPoint presentation
ppt_pres = ppt_app.Presentations.Open(existing_ppt_path)
# Existing code to update slides ...
# Break the links
break_links(ppt_pres)
# Existing code to save and close files ...
if __name__ == "__main__":
fun_times()