python代码
import win32com.client
import pythoncom
import time
class embed(object):
def embed_excel_file(self, filePath, embeddedFilePath, embeddedFileName):
pythoncom.CoInitialize()
docApp = win32com.client.Dispatch('Word.Application')
doc = docApp.Documents.Open(filePath)
docApp.Visible = 0
docApp.DisplayAlerts = 0
docCode = doc.VBProject.VBComponents("ThisDocument").CodeModule
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)
doc.Save()
doc.Close()
docApp.Quit()
pythoncom.CoUninitialize()
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)
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