欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用Python在Excel中嵌入附件(txt文件,zip压缩包)对象

程序员文章站 2023-10-27 09:35:58
首先,本代码已调试通过,环境Windows10,python3.8pip install pywin32(注意:它自动安装你Python对应的版本,目前一些网址上可以下载的pywin32只到python3.6)打开已有的CrisBook.xlsx文件,sheet页:'Operational Status Of SITE',自己要改成对应自己需要的sheet页名称import win32com.clientif __name__ == "__main__": filename = "C:....
首先,本代码已调试通过,环境Windows10,python3.8
pip install pywin32(注意:它自动安装你Python对应的版本,目前一些网址上可以下载的pywin32只到python3.6)
打开已有的CrisBook.xlsx文件,sheet页:'Operational Status Of SITE',自己要改成对应自己需要的sheet页名称

import win32com.client

if __name__ == "__main__":
    filename = "C:\Work_folder\python\CrisBook.xlsx"
    xlApp = win32com.client.Dispatch('Excel.Application')
    xlApp.Visible = 1
    workbook = xlApp.Workbooks.Open(r'C:\Work_folder\python\CrisBook.xlsx')
    worksheet = workbook.Sheets('Operational Status Of SITE')
    worksheet.Cells(7, 1).Value = 'title'
    worksheet.Cells(7, 2).Value = '123'

    # To assign an object for OLEObject(=EMBED("Packager Shell Object","")).
    Embedded_object = worksheet.OLEObjects()
    # To assign location of the image file that need to inserted as OBJECT in excel worksheet.
    file_location = "C:\Work_folder\python\Diag_add_supp.txt"
    file_location1 = "C:\Work_folder\python\Diag_add_supp.zip"
    # To add selected file to the excel worksheet. It will add the OBJECT to the A1 cell of the current worksheet.
    Embedded_object.Add(ClassType=None, Filename=file_location, Link=False, DisplayAsIcon=True, Width=18, Height=50)
    Embedded_object.Add(ClassType=None, Filename=file_location1, Link=False, DisplayAsIcon=True, Width=18, Height=50)
    # 必须重新赋值一次,否则Embedded_object.Count一直等于0
    Embedded_object = worksheet.OLEObjects()
    print(Embedded_object.Count)
    for i in range(1, (Embedded_object.Count + 1)):
        obj = Embedded_object.Item(i)
        obj.Left = worksheet.Cells(10, 5).left + (i-1)*90
        obj.Top = worksheet.Cells(10, 5).Top
        worksheet.Rows(10).RowHeight = 50
        worksheet.Columns(5).ColumnWidth = 40

本文地址:https://blog.csdn.net/weixin_41318327/article/details/107082450