初学python,分享一个简单的Excel文档合并工具

初次接触python是在2009年秋,直到现在才有认真去学习了解。

正好最近在弄工作日志,需要重复合并多个excel文档,于是折腾了一个多星期,修修补补地用python写了这么一个小东西。

1.用于合并多个excel文档,可以指定是第几个工作表,默认为最后一个工作表。

2.比较简陋,只是单纯地将每行数据合到一个文档中,并没有将格式也带到合并文档中。

3.只能用于excel2003的文档合并。

4.代码是在window下,Python自带IDEL里写的,python版本为2.7.3,

具体代码如下:

  1 ##2012-05-06 14:27
  2 # -*- coding:utf-8 -*-
  3 from Tkinter import *
  4 import tkFileDialog
  5 import tkMessageBox
  6 import os
  7 import xlrd
  8 import xlwt
  9 
 10 class combination(Frame):
 11     """combine excel files"""
 12     def __init__(self,parent=None):
 13         Frame.__init__(self,parent)
 14         self.sheetNo = 0
 15         self.filepath = []
 16         self.outpath = ""
 17         self.flag_ckbtn = IntVar()
 18         self.pack(side=TOP)
 19         self.init_entry()
 20         self.init_btn()
 21 
 22 
 23     def init_entry(self):
 24         """get sheet No by the Entry"""
 25         eframe = Frame(self)
 26         eframe.pack()
 27         Label(eframe,width=9,text='Sheet No:').pack(side='left',pady=15)
 28         en_sheetNo = Entry(eframe,width=3)
 29         en_sheetNo.pack(side='left',pady=15)
 30         en_sheetNo.bind('', (lambda event:self.getsheetNo(en_sheetNo.get())))
 31         Label(eframe,width=9,text='1st row:').pack(side='left',pady=15)
 32         ##v = IntVar()
 33         Checkbutton(eframe,onvalue=0,offvalue=1,variable=self.flag_ckbtn).pack(side='left',pady=15)
 34         
 35     def getsheetNo(self,num):
 36         """pass out sheetNo"""
 37         try:
 38             self.sheetNo = int(num)
 39         except ValueError: tkMessageBox.showinfo("Illegal Input","please input number!")
 40         
 41     def init_btn(self):
 42         """two buttons"""
 43         btn_frame = Frame(self)
 44         btn_frame.pack()
 45         btn_import = Button(btn_frame,text='Import',command=self.importx,width=8)
 46         btn_import.pack(side='left',padx=20)
 47         btn_combine = Button(btn_frame,text='Combine',command=self.combine,width=8)
 48         btn_combine.pack(side='left',padx=20)
 49 
 50     #Get filepath
 51     def importx(self):
 52         """Get input files route"""
 53         filenames = tkFileDialog.askopenfilenames()
 54         self.filepath = filenames.lstrip('{').rstrip('}').split('} {')
 55                 
 56     def combine(self):
 57         """combine excel files and write into out.xls"""
 58         if self.validation(self.filepath):
 59             allrows = self.getAllRows(self.filepath,self.sheetNo)                    
 60             path = self.filepath[0].split("/")
 61             path = "/".join(path[0:-1])+"/out.xls"
 62             self.writeIntoExcel(path,allrows)
 63 
 64     def validation(self,filepath):
 65         """Validation for excel files"""            
 66         if filepath == [''] or len(self.filepath) == 0:
 67             tkMessageBox.showinfo("Combine Failed!","You need import several Excel files before combination")
 68             return False       
 69         if filepath[0][-3:] != "xls":
 70             tkMessageBox.showinfo("Combine Failed!","Only Excel files can be combined!")
 71             return False
 72         return True
 73         
 74 
 75     def getAllRows(self,filepath,sheetNo):
 76         """combine all rows into a list"""
 77         allrows = []        #clear before store rows
 78         for fname in filepath:
 79             try:
 80                 data = xlrd.open_workbook(fname)
 81             except IOError:
 82                 tkMessageBox.showinfo("IOError","Please select at least one file!")
 83                 return
 84             
 85             #get sheet number
 86             if sheetNo in range(data.nsheets+1):
 87                 pass
 88             else: sheetNo = data.nsheets
 89             table = data.sheet_by_index(sheetNo-1)
 90             
 91             #import all rows except or inculde the first one
 92             for rownum in range(self.flag_ckbtn.get(),table.nrows):
 93                 row = table.row_values(rownum)
 94                 fa = cmp(row[0].encode("utf-8"), "") # fa=0 if no value in first columen
 95                 fb = cmp(row[0].encode("utf-8"), "在此前复制并插入行") # fb=0 if equal the special value
 96                 colnum = len(row)
 97                 if fa!=0 and fb!=0 and row:
 98                     app=[]
 99                     for i in range(colnum):
100                         app.append(row[i])
101                     allrows.append(app)
102         return allrows
103 
104     def writeIntoExcel(self,path,allrows):
105         """write list into an excel file"""
106         wbk = xlwt.Workbook()
107         sheet = wbk.add_sheet('combined sheet')
108         for i in range(len(allrows)):
109             for j in range(len(allrows[i])):
110                 sheet.write(i,j,allrows[i][j])
111         #wbk.save(unicode(path,"utf-8"))
112         try:
113             wbk.save(path)
114         except IOError:
115             tkMessageBox.showinfo("Generate Failed!","Please close 'out.xls'")
116             return
117         tkMessageBox.showinfo("Combination Finished!","The combined file locate at: "+path)
118         return
119         
120                 
121 root = Tk()
122 root.title("Excel files combination")
123 root.geometry("240x100+550+300")
124 comb = combination(root)
125 root.mainloop()

转载于:https://www.cnblogs.com/Alex-Python-Waiter/archive/2012/05/10/excelCombination.html

你可能感兴趣的:(初学python,分享一个简单的Excel文档合并工具)