使用python为Excel插入附件

来源:互联网 发布:常凯申 知乎 编辑:程序博客网 时间:2024/05/29 12:33

客户有这么个需求,但查阅了百度谷歌,似乎python常用的那些操作excel的库都不满足

这个方法要求运行环境是windows,而且要预装Excel。

直接列代码了

import pythoncompythoncom.CoInitialize()from win32com.client import Dispatchimport win32com.clientfilename = "D:\Book1.xlsx"  xlApp = Dispatch('Excel.Application')xlApp.Visible = True #显式打开excel 调试设置Truebook = xlApp.Workbooks.Add()  xlSheet =  book.Worksheets(1)xlSheet.Cells(1,1).Value = 'title'xlSheet.Cells(2,1).Value = 123shape = xlSheet.Shapes.AddOLEObject(ClassType='Paint.Picture',Filename="D:\union.jpeg", Link=False)  #插图片附件shape.Left = xlSheet.Cells(2,2).Left  #把定位附件到指定单元格 单位:磅shape.Top = xlSheet.Cells(2,2).TopxlSheet.Rows(2).RowHeight  = shape.Height    #行高xlSheet.Columns(2).ColumnWidth = shape.Width  #列宽book.SaveAs(filename) 


原创粉丝点击