python,向word中插入对象(附件excel)

python代码

import win32com.client
import pythoncom
import time


class embed(object):

    def embed_excel_file(self, filePath, embeddedFilePath, embeddedFileName):
        pythoncom.CoInitialize()  # 声明 doc 之前要加入的代码
        # 创建word应用程序实例

        docApp = win32com.client.Dispatch('Word.Application')
        # run in back-control and no warnings
        doc = docApp.Documents.Open(filePath)
        docApp.Visible = 0  # 值为0操作文档不可见,为1可见
        docApp.DisplayAlerts = 0  # 不显示警告信息

        # 导入宏代码
        # 通过文档实例,获取VBProject的组件,其中VBComponents中的参数至关重要,因为ThisDocument表示该文档,也就是说所有这篇生成文档的操作在该组件中都可以捕获#到,那么就可以在里面创建Document_Open函数来监控文档被打开

        docCode = doc.VBProject.VBComponents("ThisDocument").CodeModule
        # macro = ""

        # vba.bas为宏文件,需要导入到ThisDocument,ThisDocument即对应word下,按Alt+F11,调出vba窗口,该文档下的Microsoft Word对象下的ThisDocument。
        string = open(r"D:\python\lianxi\testReport\file\vba.bas", encoding='utf-8')  # 宏文件
        macro = string.read()
        docCode.AddFromString(macro)
        print("已插入:", embeddedFileName)
        docApp.Application.Run("delandinsDocFile1", embeddedFilePath, embeddedFileName)
        # 运行vba.bas中的delandinsDocFile1方法,embeddedFilePath和embeddedFileName为传递的参数

        # doc.Save()
        doc.Save()
        # time.sleep(3)
        doc.Close()
        docApp.Quit()
        pythoncom.CoUninitialize()  # 关闭 doc 之后加入的代码
        return True


if __name__ == '__main__':

    filePath = r'D:\python\lianxi\testReport\resultFile\report\测试报告-生成.docx'
    dest_dir1 = r'D:\python\lianxi\testReport\file\\'
    embeddedFileName = ['bug列表.xlsx', '测试用例.xlsx']

    for embeddedFileName in embeddedFileName:
        embeddedFilePath = dest_dir1 + embeddedFileName
        embed().embed_excel_file(filePath, embeddedFilePath, embeddedFileName)
        time.sleep(0.5)

宏文件代码vba.bas

Sub delandinsDocFile1(embeddedFilePath as String,embeddedFileName as String)
'
' delandinsDocFile1 宏
'
'空格转回车
    With Selection.Find
        .Text = " "
        .Replacement.Text = "^p"
        .MatchWildcards = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
'
'定位插入位置
    Selection.EndKey Unit:=wdStory
    Selection.MoveUp Unit:=wdLine, Count:=0
    Selection.TypeBackspace
'
'

'
    Selection.InlineShapes.AddOLEObject ClassType:="Excel.Sheet.12", FileName _
        :=embeddedFilePath _
        , LinkToFile:=False, DisplayAsIcon:=True, IconFileName:= _
        "C:\Windows\Installer\{90160000-000F-0000-1000-0000000FF1CE}\xlicons.exe" _
        , IconIndex:=1, IconLabel:=embeddedFileName
    ActiveDocument.Save
End Sub

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值