简体   繁体   English

Python Win32com将Word对象插入Excel文件

[英]Python win32com insert word object into Excel file

Excel error: "Document not saved" when trying to insert multiple objects into excel file. Excel错误:尝试将多个对象插入excel文件时出现“未保存文档”。 Works for zip and .mpp file extensions, but not working with .doc and .docx file types. 适用于zip和.mpp文件扩展名,但不适用于.doc和.docx文件类型。 Once inserted, the object shows a white unknown file image and simply says EMBED("Document",""). 插入后,该对象将显示白色的未知文件图像,并简单地说EMBED(“ Document”,“”)。 However, when I insert manually these docs I have no problems and they display as Word doc icon. 但是,当我手动插入这些文档时,我没有任何问题,它们显示为Word doc图标。 Any Suggestions? 有什么建议么?

import win32com.client as win32
xl = win32.gencache.EnsureDispatch('Excel.Application')
xl.Visible = 1
wb = xl.Workbooks.Open('BlankTemplate.xlsx')  #New Excel file that is blank
xl.DisplayAlerts = False
ws = wb.Worksheets('Sheet1')
dest_cell = ws.Range('C5')
obj = ws.OLEObjects()

obj.Add(ClassType=None,Filename='Approval.zip',Link=False,DisplayAsIcon=False,Left=dest_cell.Left, Top=dest_cell.Top,Width=50,Height=50) obj.Add(ClassType=None,Filename='Final.docx',Link=False,DisplayAsIcon=True,Left=dest_cell.Left, Top=dest_cell.Top,Width=50,Height=50) obj.Add(ClassType=None,Filename='Release.doc',Link=False,DisplayAsIcon=True,Left=dest_cell.Left, Top=dest_cell.Top,Width=50,Height=50) obj.Add(ClassType=None,Filename='Platform.mpp',Link=False,DisplayAsIcon=False,Left=dest_cell.Left, Top=dest_cell.Top,Width=50,Height=50) obj.Add(ClassType = None,Filename ='Approval.zip',Link = False,DisplayAsIcon = False,Left = dest_cell.Left,Top = dest_cell.Top,Width = 50,Height = 50)obj.Add(ClassType =无,文件名='Final.docx',链接= False,DisplayAsIcon = True,左= dest_cell.Left,顶部= dest_cell.Top,宽度= 50,高度= 50)obj.Add(ClassType = None,文件名='Release .doc',Link = False,DisplayAsIcon = True,Left = dest_cell.Left,Top = dest_cell.Top,Width = 50,Height = 50)obj.Add(ClassType = None,Filename ='Platform.mpp',Link = False,DisplayAsIcon = False,左= dest_cell.Left,顶= dest_cell.Top,宽度= 50,高度= 50)

wb.SaveAs('ProjectDetailsAttachments.xlsx')
xl.DisplayAlerts = True
xl.Application.Quit()
xl.Visible = 0    

I figured it out!! 我想到了!! I recorded a Excel VBA macro in order to see what it uses to insert a word document object and found they have a few additional parameters added, once i added them it works now. 我记录了一个Excel VBA宏,以查看其用于插入Word文档对象的作用,发现它们添加了一些其他参数,一旦添加它们,它现在就可以使用了。

wordpath = 'C\\Program Files (x86)\\Microsoft Office\\Office 14\\WINWORD.EXE'
obj.Add(ClassType=None,Filename='Final.docx',Link=False,DisplayAsIcon=True, \ 
    IconFileName=wordpath,IconIndex=0,IconLabel=Final.docx \ 
    Left=dest_cell.Left, Top=dest_cell.Top,Width=50,Height=50) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM