Python 合併文件夾下所有的Excel文件

打開windows窗口選擇文件( askopenfilename( ) )文件夾 ( askdirectory() ),以下代碼是打開文件夾和文件的示例。

import tkinter.filedialog as tkFD

def __init__(self, root):
    self.ext1 = Button(self.frame[1], text="選擇文件", command=self.openfile,width = 10)
        self.ext1.pack(side = LEFT, padx = 2,pady = 10)
        self.txt = Text(self.frame[1],height = 1,width = 80)
        self.txt.pack(side = LEFT, padx = 2,pady = 10)

        self.ext3 = Button(self.frame[3], text="選擇根目錄", command=self.opendir,width = 10)
        self.ext3.pack(side = LEFT, padx = 2,pady = 10)       
        self.path = Text(self.frame[3],height = 1,width = 40)
        self.path.pack(side = LEFT, padx = 2,pady = 10)

def openfile(self):
        self.filename=tkFD.askopenfilename(filetypes=[("Excel 工作簿", ".xls")])
        self.txt.delete(1.0,END)
        self.txt.insert(1.0,self.filename)
   
def opendir(self):
        self.pathname=tkFD.askdirectory()
        self.path.delete(1.0,END)
        self.path.insert(1.0,self.pathname)

 

同一個文件夾存在數量衆多的Excel文件,比如某次活動郵件發送的Excel報名文件、各類記錄等,需要手動對記錄進行一條條的複製粘貼合併,快速的合併方式是通過pandas讀取文件夾下的所有的Excel文件,然後統一合併。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import os
from Tkinter import *
from tkFileDialog import *

class App:
    def __init__(self, root):
        frame = Frame(root)  # container
        frame.pack()

        self.button1 = Button(frame, text="Excel文件夾", command=self.filefound1, width=20, height=1).grid(row=0, column=0)
        self.button2 = Button(frame, text="運行", command=self.eachFile, width=20, height=1).grid(row=3, column=0)
        self.button3 = Button(frame, text="退出", command=frame.quit, width=20, height=1).grid(row=4, column=0)

        self.e = Entry(frame)
        self.e.grid(row=0, column=2)
        self.e.delete(0, END)  # 將輸入框裏面的內容清空
        self.e.insert(0, '顯示文件路徑')

        self.filepath = StringVar()
        self.frames = []

    def filefound1(self):
        self.filepath = askdirectory()
        print self.filepath
        self.e.delete(0, END)  # 將輸入框裏面的內容清空
        self.e.insert(0, self.filepath)
        return self.filepath

    # 遍歷指定目錄,顯示目錄下的所有文件名
    def eachFile(self):
        pathDir = os.listdir(self.filepath)
        for allDir in pathDir:
            if allDir[-4:] == 'xlsx' or allDir[-4:] == 'xls':
                child = os.path.join('%s\%s' % (self.filepath, allDir))
                print child  # .decode('gbk')是解決中文顯示亂碼問題
                df = pd.DataFrame(pd.read_excel(child))
                self.frames.append(df)
        result = pd.concat(self.frames)
        # 保存文件
        savepath = self.filepath + u'\\excel_to_python.xlsx'
        result.to_excel(savepath, sheet_name='bluewhale_cc')

if __name__ == '__main__':
    root = Tk()
    root.title('Excel文件合併')
    app = App(root)
    root.mainloop()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章