#!/usr/bin/env python# -*- coding: utf-8 -*-# Last Update:'''covert many excel files to one word file'''__revision__='0.1'__author__='lxd'fromwin32com.clientimportDispatchimportoswdPageBreak=7defisExcelFile(name):returnos.path.isfile(name)andos.path.splitext(name)[1]=='.xls'deffilesInDir(dir):#generate absolute paths of files in a directoryforroot,dirs,filesinos.walk(dir):forfileinfiles:yieldos.path.join(root,file)deffindExcels(names):fornameinnames:ifisExcelFile(name):yieldnameelse:forfileinfilesInDir(name):ifisExcelFile(file):yieldfileclassExcelToWord(object):def__init__(self,excelNames,wordName):self._createExcel()self.excelNames=findExcels(excelNames)self._createWord()self.word.Documents.Open(wordName)def_createExcel(self):self.excel=Dispatch('Excel.Application')#self.excel.Visible = Trueself.excel.DisplayAlerts=Falsedef_createWord(self):self.word=Dispatch('Word.Application')self.word.Visible=Trueself.word.DisplayAlerts=Falsedefprocess(self):forexcelNameinself.excelNames:print'coverting',excelNameself.excel.Workbooks.Open(excelName)foriinrange(self.excel.Worksheets.count):self.excel.Worksheets(i+1).Select()#start from 1self._copy()self._paste()self.excel.Workbooks.Close()self.excel.Quit()print'covert is over'def_copy(self):# select all contents in one sheet and copyself.excel.Cells.Select()self.excel.Selection.Copy()def_paste(self):#paste to one word file and add a page breakself.word.Selection.Paste()#self.word.Selection.TypeParagraph()self.word.Selection.InsertBreak(wdPageBreak)if__name__=='__main__':excelNames=[u'c:\\users\\lxd\\desktop\\文档',u'c:\\users\\lxd\\desktop\\汇总.xls',]wordName=r'c:\users\lxd\desktop\1.doc'e=ExcelToWord(excelNames,wordName)e.process()