python用win32com处理excel表格
今天一同事让处理一个excel,把一个excel里固定位置的内容读取写到另一个excel中的固定位置里,查了一些资料,python有好多处理excel的模块,对比之后感觉用win32com来处理这个问题比较简单,其中包含了处理文件路径和文件名字为中文的编码问题,下面是自己写的代码:#!/usr/bin/env python # -- coding: utf-8 --from win32com.client import constants,Dispatch import os,sys,datetime,time,shutilclass rw_excel: def __init__(self): self.yesterday = (datetime.date.today() - datetime.timedelta(days=2)).strftime('%Y%m%d') self.cwd = os.getcwd() def read_excel(self): try: f = self.cwd + "\\" + self.yesterday + "\\" + u"汇总".encode("gbk") + "_" + self.yesterday + ".xlsx" print f f_open = (f) xlsApp = Dispatch("Excel.Application") xlsApp.Visible = False xlsBook = xlsApp.Workbooks.Open(f_open) sheet_name = ('统计').decode("utf8") xlsSht = xlsBook.Worksheets(sheet_name) R = [] open = [,,,,,,,,,,,,,] for i in open: a = xlsSht.Cells(i,i).Value.encode("utf8") R.append(a) return R except Exception,e: print e def write_excel(self,R): f = self.cwd + "\\" + self.yesterday + "\\" + u"数量汇总".encode("gbk") + "(GY)_" + self.yesterday + ".xls" print f f_save = (f) xlsApp = Dispatch("Excel.Application") xlsApp.Visible = False xlsBook = xlsApp.Workbooks.Open(f_save) sheet_name = ('数量汇总(GY)').decode("utf8") xlsSht = xlsBook.Worksheets(sheet_name) save = [,,,,,,,,,,,,,] for i in range(len(R)): xlsSht.Cells(save,save).Value = R xlsBook.Close(SaveChanges=1) xlsApp.Quit() def main(self): R = self.read_excel() print "read_excel OK" self.write_excel(R) print "write_excel GY OK" print "Excel OK"class move: def __init__(self): self.yesterday = (datetime.date.today() - datetime.timedelta(days=2)).strftime('%Y%m%d') self.cwd = os.getcwd() def copy(self,src, dst): if os.path.isdir(src): base = os.path.basename(src) if os.path.exists(dst): dst = os.path.join(dst, base) if not os.path.exists(dst): os.makedirs(dst) names = os.listdir(src) for name in names: srcname = os.path.join(src, name) self.copy(srcname, dst) else: shutil.copy2(src, dst) def mk_dir(self): a = self.cwd + "\\" + u"处理名单_%s".encode("gbk") % self.yesterday + "\\" + u"处理名单(GY)_%s".encode("gbk") % self.yesterday print a if not os.path.isdir(a): os.makedirs(a) b = self.cwd + "\\" + u"处理名单_%s".encode("gbk") % self.yesterday + "\\" + u"处理名单(CS)_%s".encode("gbk") % self.yesterday print b if not os.path.isdir(b): os.makedirs(b) f = self.cwd + "\\" + self.yesterday + "\\" names = os.listdir(f) for name in names: if "txt" in name or "CS" in name: self.copy(os.path.join(f,name),os.path.join(b,name)) else: self.copy(os.path.join(f,name),os.path.join(a,name)) shutil.rmtree(f) print "Move ok" def main(self): self.mk_dir()if __name__=="__main__": boss = rw_excel() boss.main() boss = move() boss.main() 以下是运行打印的结果:
页:
[1]