Python win32com模塊 合併文件夾內多個docx文件爲一個docx

Python win32com模塊 合併文件夾內多個docx文件爲一個docxpython

#!/usr/bin/env python     
# -*- coding: utf-8 -*-     
from win32com.client import Dispatch
import os,sys
#import pandas as pd

#下面三句是爲了能取得系統自帶常量
from win32com.client import constants as con
#from win32com.client.gencache import EnsureDispatch
#EnsureDispatch('Word.Application')
def mkdir(path):
    # 引入模塊
    # import os

    # 去除首位空格
    # path=path.strip()
    # 去除尾部 \ 符號
    # path=path.rstrip("\\")

    # 判斷路徑是否存在
    # 存在     True
    # 不存在   False
    isExists=os.path.exists(path)

    # 判斷結果
    if not isExists:
        # 若是不存在則建立目錄
        # 建立目錄操做函數
        os.makedirs(path) 
        print(path+'建立成功')
        return True
    else:
        # 若是目錄存在則不建立,並提示目錄已存在
        print(path+' 目錄已存在')
        return False


pwd=__file__
pwd=os.path.dirname(pwd)
print(pwd)

mkdir(os.path.join(pwd,'hebing'))
#xlApp=Dispatch('Excel.Application')
wdApp=Dispatch('Word.Application')
#xlApp.Visible=1

docB=wdApp.Documents.Add()
#=====頁面設置======
ps=56.7
docB.PageSetup.TopMargin=ps
docB.PageSetup.BottomMargin=ps
docB.PageSetup.LeftMargin=ps
docB.PageSetup.RightMargin=ps
docB.SaveAs(pwd + '\\hebing\\hebing.docx',14)
#======保存文檔=========


for root,dirs,files in os.walk(os.path.join(pwd,'放word文檔的文件夾'),topdown=False):
    print(files)
    for name in files:
        docT=wdApp.Documents.Open(os.path.join(root,name))
        #docT.Range(0,0)#光標定位文檔開始
        wdApp.Selection.WholeStory()#全選word文檔
        wdApp.Selection.Copy()
        docB.Activate()
        #wdApp.Selection.EndKey(Unit=con.wdLine)       
        docB.Range()#光標定位文檔結束
        wdApp.Selection.Delete()
        wdApp.Selection.Paste()
        
        docT.Close()
    
docB.Save()
docB.Close()
wdApp.Quit()
相關文章
相關標籤/搜索