詳解Python如何實(shí)現(xiàn)Excel數(shù)據(jù)讀取和寫(xiě)入
1. 功能分析
1.加載文件夾內(nèi)所有的Excel數(shù)據(jù);
2.生產(chǎn)貢獻(xiàn)度分析圖表(以柱狀圖顯示表格數(shù)據(jù));
3.提起Excel表格中指定列數(shù)據(jù);
4.定向篩選所需數(shù)據(jù);
5.多表數(shù)據(jù)統(tǒng)計(jì)排行;
6.多表數(shù)據(jù)合并新excel文件。
2.系統(tǒng)開(kāi)發(fā)環(huán)境
Anaconda3,在conda 中,window和ubuntu中的python功能一樣 。
pycharm。
3.安裝依賴(lài)庫(kù)
這些依賴(lài)包 都要裝好
import os import xlrd2 #xlrd: 對(duì)Excel進(jìn)行讀相關(guān)操作 import xlwt #xlwt: 對(duì)Excel進(jìn)行寫(xiě)相關(guān)操作,且只能創(chuàng)建一個(gè)全新的Excel然后進(jìn)行寫(xiě)入和保存。 import numpy import matplotlib from prettytable import PrettyTable #PrettyTable 是python中的一個(gè)第三方庫(kù),可用來(lái)生成美觀的ASCII格式的表格 from matplotlib import pyplot as plt
4. 主函數(shù)設(shè)計(jì)
Excel數(shù)據(jù)分析師的主函數(shù)main(),主要用于實(shí)現(xiàn)系統(tǒng)的主界面。在主函數(shù)main()中,首先調(diào)用get_files_name()函數(shù)獲取文件名。
get_files_name()函數(shù)代碼如下:
#導(dǎo)入文件 def get_files_name(): """ 用于獲取文件名 :return: 返回值為文件名組成的列表 """ file_list = os.listdir('./data') return file_list
然后調(diào)用load_data()函數(shù)來(lái)讀取excel文件并字典方式保存。
#保存生產(chǎn)excel表 def load_data(file_list): """ 用于讀取指定的文件并保存至字典數(shù)據(jù)結(jié)構(gòu)中 :param file_list: 需要加載的文件列表 :return: 保存了文件內(nèi)容的字典 """ dictory = {} for file in file_list: # 獲取表格文件 book = xlrd2.open_workbook('./data/'+file) # 獲取表格中的所有sheet names = book.sheet_names() # 獲取第一個(gè)sheet sheet = book.sheet_by_index(0) # 獲取當(dāng)前表格的行數(shù) rows = sheet.nrows # 獲取當(dāng)前表格的列數(shù) cols = sheet.ncols # 獲取表頭文件,即表格第一行 head = sheet.row_values(0) for row in range(rows-1): # 如果當(dāng)前字典中沒(méi)有該城市則創(chuàng)建一個(gè) if not sheet.cell_value(row+1, 0) in dictory.keys(): dictory[sheet.cell_value(row+1, 0)] = {} for col in range(cols-1): dictory[sheet.cell_value(row+1, 0)][head[col+1]] = float(sheet.cell_value(row+1, col+1)) return dictory
接著調(diào)用menu()函數(shù)生成功能選擇菜單。
menu()函數(shù)代碼如下:
# 打印菜單 def menu(): print(" ----------Excel 數(shù)據(jù)分析師----------") print("{:<30}".format(" ==============功能菜單============== ")) print("{:<30}".format(" 1. 顯示當(dāng)前數(shù)據(jù) ")) print("{:<30}".format(" 2. 以柱狀圖展示當(dāng)前數(shù)據(jù) ")) print("{:<30}".format(" 3. 提起指定列 ")) print("{:<30}".format(" 4. 定向篩選指定元素 ")) print("{:<30}".format(" 5. 數(shù)據(jù)排行 ")) print("{:<30}".format(" 6. 重新加載數(shù)據(jù) ")) print("{:<30}".format(" 7. 保存當(dāng)前數(shù)據(jù) ")) print("{:<30}".format(" 0. 退出程序 ")) print("{:<30}".format(" ==================================== ")) print("{:<30}".format(" 說(shuō)明:輸入相應(yīng)數(shù)字后按下回車(chē)選擇指定功能 ")) print('\n')
并且應(yīng)用if語(yǔ)句控制各個(gè)子函數(shù)的調(diào)用,從而實(shí)現(xiàn)對(duì)Excel文件的選擇,Excel數(shù)據(jù)的加載,選擇、篩選、合并、排序和統(tǒng)計(jì)等功能。
主函數(shù)完整代碼如下:
if __name__ == "__main__": # 導(dǎo)入文件 files = get_files_name() data = {} print("當(dāng)前data文件夾下的文件如下:") num = 1 for file in files: print(num, file) num += 1 while(1): index_str = input("請(qǐng)選擇需要導(dǎo)入的文件序號(hào)(多個(gè)文件導(dǎo)入時(shí)用空格分開(kāi), 輸入0則導(dǎo)入所有文件,輸入多文件則自動(dòng)合并):") index_list = index_str.split(' ') try: index_list.remove('') except: pass choice_file_list = [] if index_list[0] == '0': choice_file_list = files break else: try: for item in index_list: choice_file_list.append(files[int(item)-1]) except: print("輸入序號(hào)有誤") continue if choice_file_list: break else: print("輸入序號(hào)有誤") data = load_data(choice_file_list) print("導(dǎo)入數(shù)據(jù)成功\n") # 調(diào)用函數(shù),打印菜單 menu() while 1: choice = input("請(qǐng)選擇指定功能:") if choice == '0': print("\n退出程序\n") exit() elif choice == '1': print("當(dāng)前功能:顯示當(dāng)前數(shù)據(jù)") show_data(data) input('\n按下回車(chē)返回菜單') menu() elif choice == '2': print("當(dāng)前功能:以柱狀圖顯示數(shù)據(jù)") draw_plot(data) input('\n按下回車(chē)返回菜單') menu() elif choice == '3': print("當(dāng)前功能:篩選指定列") keys = list(data[list(data.keys())[0]].keys()) print("當(dāng)前表格中的列如下:") num = 1 for key in keys: print(num, key) num += 1 choice_col_list = [] while (1): index_str = input("請(qǐng)選擇需要篩選出的列序號(hào)(多列之間用空格分開(kāi),0代表所有列):") index_list = index_str.split(' ') try: index_list.remove('') except: pass choice_file_list = [] if index_list[0] == '0': choice_col_list = keys break else: try: for item in index_list: choice_col_list.append(keys[int(item) - 1]) except: print("輸入序號(hào)有誤") continue if choice_col_list: break else: print("輸入序號(hào)有誤") data = get_specified_cols(data, choice_col_list) print("篩選成功") input('\n按下回車(chē)返回菜單') menu() elif choice == '4': print("當(dāng)前功能:篩選指定行") keys = list(data[list(data.keys())[0]].keys()) print("當(dāng)前表格中的列如下:") num = 1 print(num, "城市") num += 1 for key in keys: print(num, key) num += 1 col = int(input("請(qǐng)輸入需要進(jìn)行篩選的數(shù)據(jù)所在的列:"))-2 if col == -1: col = '城市' else: col = keys[col] op_list = ['<', '<=', '=', '>=', '>'] print("比較操作符如下:") num = 1 for op in op_list: print(num, op) num += 1 operation = int(input("請(qǐng)輸入比較操作符前的序號(hào):"))-1 operation = op_list[operation] value = input("請(qǐng)輸入需要篩選的值:") data = get_specified_data(data, operation, col, value) print("篩選成功") input('\n按下回車(chē)返回菜單') menu() elif choice == '5': print("當(dāng)前功能:數(shù)據(jù)排序") keys = list(data[list(data.keys())[0]].keys()) print("當(dāng)前表格中的列如下:") num = 1 for key in keys: print(num, key) #顯示當(dāng)前表格中的所有的列 num += 1 col = int(input("請(qǐng)輸入需要進(jìn)行排序的數(shù)據(jù)所在的列:")) - 1 col = keys[col] reverse = input("排序方式:\n1 從大到小排序\n2 從小到大排序\n") if reverse == '1': data = sort_data(data, col, True) elif reverse == '2': data = sort_data(data, col, False) else: print("輸入有誤") input('\n按下回車(chē)返回菜單') menu() elif choice == '6': # 導(dǎo)入文件 files = get_files_name() data = {} print("當(dāng)前文件夾下的文件如下:") num = 1 for file in files: print(num, file) num += 1 while (1): index_str = input("請(qǐng)選擇需要導(dǎo)入的文件序號(hào)(多個(gè)文件導(dǎo)入時(shí)用空格分開(kāi), 輸入0則導(dǎo)入所有文件,輸入多文件則自動(dòng)合并):") index_list = index_str.split(' ') try: index_list.remove('') except: pass choice_file_list = [] if index_list[0] == '0': choice_file_list = files break else: try: for item in index_list: choice_file_list.append(files[int(item) - 1]) except: print("輸入序號(hào)有誤") continue if choice_file_list: break else: print("輸入序號(hào)有誤") data = load_data(choice_file_list) print("導(dǎo)入數(shù)據(jù)成功\n") # 打印菜單 menu() elif choice == '7': print("當(dāng)前功能:保存數(shù)據(jù)") save(data) input('\n按下回車(chē)返回菜單') menu() else: print("請(qǐng)輸入正確的數(shù)字") input('\n按下回車(chē)返回菜單') menu()
5.模塊設(shè)計(jì)
加載文件夾內(nèi)所有的Excel數(shù)據(jù)
show_data()函數(shù)通過(guò)PrettyTable 庫(kù)(PrettyTable 庫(kù)是python中的一個(gè)第三方庫(kù),可用來(lái)生成美觀的ASCII格式的表格)將之前保存的字典數(shù)據(jù)生成表格。
#加載顯示數(shù)據(jù) def show_data(dictory): try: keys = list(dictory[list(dictory.keys())[0]].keys()) except: print("當(dāng)前數(shù)據(jù)為空") return head = ['城市'] head.extend(keys) table = PrettyTable(head) for key in dictory.keys(): line = [key] for key_2 in keys: line.append(dictory[key][key_2]) table.add_row(line) print(table)
效果圖如下:
生產(chǎn)貢獻(xiàn)度分析圖表(以柱狀圖顯示表格數(shù)據(jù))
draw_plot( )函數(shù)使用了matplotlib庫(kù)。通過(guò)atplotlib.rc( )來(lái)設(shè)置字體,通過(guò)plt.bar( )函數(shù)來(lái)繪制柱狀圖,通過(guò)plt.legend( )函數(shù)來(lái)給圖添加圖例。
#制作圖表 def draw_plot(dictory): font = {'family': 'MicroSoft Yahei', 'weight': 'bold', 'size': 7} matplotlib.rc('font', **font) #設(shè)置中文字體 # 定義三個(gè)顏色 index = numpy.arange(len(dictory.keys())) color = [(256 / 256, 0 / 256, 0 / 256, 1), (0 / 256, 0 / 256, 256 / 256, 1), (0 / 256, 256 / 256, 0 / 256, 1), (0 / 256, 0 / 256, 0 / 256, 1)] first_key = list(dictory.keys()) first_key = first_key[0] cols = list(dictory[first_key].keys()) data = [] for i in range(len(cols)): data.append([]) for key in dictory.keys(): for col in range(len(cols)): data[col].append(dictory[key][cols[col]]) offset = -1/4 for i in range(len(cols)): plt.bar(index+offset, data[i], color=color[i], width=1 / 5) #通過(guò)bar函數(shù)可以用柱狀圖來(lái)表達(dá)一些變量的統(tǒng)計(jì)分布 offset += 1/4 plt.xticks(index, dictory.keys())#表示刻度 plt.legend(cols)#給圖像加上圖例 plt.show()
效果圖
提起Excel表格中指定列數(shù)據(jù)
get_specified_cols()函數(shù)根據(jù)用戶(hù)在菜單輸入的列名,通過(guò)字典的索引篩選出列名,加載指定列的所有數(shù)據(jù)。
#提起指定列 def get_specified_cols(dictory, col_name_list): """ 篩選出指定的列 :param dictory:原始字典 :param col_name_list: 需要篩選出的列名,城市名默認(rèn)出現(xiàn) :return: 篩選之后的字典 """ new_dict = {} for key in dictory.keys(): new_dict[key] = {} for col_name in col_name_list: new_dict[key][col_name] = dictory[key][col_name] return new_dict
效果圖如下:
到此這篇關(guān)于詳解Python如何實(shí)現(xiàn)Excel數(shù)據(jù)讀取和寫(xiě)入的文章就介紹到這了,更多相關(guān)Python Excel數(shù)據(jù)讀寫(xiě)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python 輸出列表元素實(shí)例(以空格/逗號(hào)為分隔符)
今天小編就為大家分享一篇python 輸出列表元素實(shí)例(以空格/逗號(hào)為分隔符),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12Python configparser模塊配置文件解析與應(yīng)用探究
在Python中,configparser模塊是用于處理配置文件的重要工具,本文將全面探討configparser模塊的使用方法,包括讀取、修改、寫(xiě)入配置文件,以及如何在實(shí)際項(xiàng)目中應(yīng)用該模塊,結(jié)合豐富的示例代碼,將深入剖析該模塊的功能和靈活性2024-01-01Python實(shí)現(xiàn)圖片轉(zhuǎn)字符畫(huà)的示例代碼
本篇文章主要介紹了Python實(shí)現(xiàn)圖片轉(zhuǎn)字符畫(huà)的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08python自定義函數(shù)def的應(yīng)用詳解
這篇文章主要介紹了python自定義函數(shù)def的應(yīng)用詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06python類(lèi)別數(shù)據(jù)數(shù)字化LabelEncoder?VS?OneHotEncoder區(qū)別
這篇文章主要為大家介紹了機(jī)器學(xué)習(xí):數(shù)據(jù)預(yù)處理之將類(lèi)別數(shù)據(jù)數(shù)字化的方法LabelEncoder?VS?OneHotEncoder區(qū)別詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09Python進(jìn)程,多進(jìn)程,獲取進(jìn)程id,給子進(jìn)程傳遞參數(shù)操作示例
這篇文章主要介紹了Python進(jìn)程,多進(jìn)程,獲取進(jìn)程id,給子進(jìn)程傳遞參數(shù)操作,結(jié)合實(shí)例形式分析了Python多進(jìn)程、父子進(jìn)程以及進(jìn)程參數(shù)傳遞相關(guān)操作技巧,需要的朋友可以參考下2019-10-10