詳解Python如何實現(xiàn)Excel數(shù)據(jù)讀取和寫入
1. 功能分析
1.加載文件夾內(nèi)所有的Excel數(shù)據(jù);
2.生產(chǎn)貢獻度分析圖表(以柱狀圖顯示表格數(shù)據(jù));
3.提起Excel表格中指定列數(shù)據(jù);
4.定向篩選所需數(shù)據(jù);
5.多表數(shù)據(jù)統(tǒng)計排行;
6.多表數(shù)據(jù)合并新excel文件。
2.系統(tǒng)開發(fā)環(huán)境
Anaconda3,在conda 中,window和ubuntu中的python功能一樣 。
pycharm。
3.安裝依賴庫

這些依賴包 都要裝好
import os import xlrd2 #xlrd: 對Excel進行讀相關(guān)操作 import xlwt #xlwt: 對Excel進行寫相關(guān)操作,且只能創(chuàng)建一個全新的Excel然后進行寫入和保存。 import numpy import matplotlib from prettytable import PrettyTable #PrettyTable 是python中的一個第三方庫,可用來生成美觀的ASCII格式的表格 from matplotlib import pyplot as plt
4. 主函數(shù)設(shè)計
Excel數(shù)據(jù)分析師的主函數(shù)main(),主要用于實現(xiàn)系統(tǒng)的主界面。在主函數(shù)main()中,首先調(diào)用get_files_name()函數(shù)獲取文件名。
get_files_name()函數(shù)代碼如下:
#導入文件
def get_files_name():
"""
用于獲取文件名
:return: 返回值為文件名組成的列表
"""
file_list = os.listdir('./data')
return file_list
然后調(diào)用load_data()函數(shù)來讀取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()
# 獲取第一個sheet
sheet = book.sheet_by_index(0)
# 獲取當前表格的行數(shù)
rows = sheet.nrows
# 獲取當前表格的列數(shù)
cols = sheet.ncols
# 獲取表頭文件,即表格第一行
head = sheet.row_values(0)
for row in range(rows-1):
# 如果當前字典中沒有該城市則創(chuàng)建一個
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. 顯示當前數(shù)據(jù) "))
print("{:<30}".format(" 2. 以柱狀圖展示當前數(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. 保存當前數(shù)據(jù) "))
print("{:<30}".format(" 0. 退出程序 "))
print("{:<30}".format(" ==================================== "))
print("{:<30}".format(" 說明:輸入相應(yīng)數(shù)字后按下回車選擇指定功能 "))
print('\n')
并且應(yīng)用if語句控制各個子函數(shù)的調(diào)用,從而實現(xiàn)對Excel文件的選擇,Excel數(shù)據(jù)的加載,選擇、篩選、合并、排序和統(tǒng)計等功能。
主函數(shù)完整代碼如下:
if __name__ == "__main__":
# 導入文件
files = get_files_name()
data = {}
print("當前data文件夾下的文件如下:")
num = 1
for file in files:
print(num, file)
num += 1
while(1):
index_str = input("請選擇需要導入的文件序號(多個文件導入時用空格分開, 輸入0則導入所有文件,輸入多文件則自動合并):")
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("輸入序號有誤")
continue
if choice_file_list:
break
else:
print("輸入序號有誤")
data = load_data(choice_file_list)
print("導入數(shù)據(jù)成功\n")
# 調(diào)用函數(shù),打印菜單
menu()
while 1:
choice = input("請選擇指定功能:")
if choice == '0':
print("\n退出程序\n")
exit()
elif choice == '1':
print("當前功能:顯示當前數(shù)據(jù)")
show_data(data)
input('\n按下回車返回菜單')
menu()
elif choice == '2':
print("當前功能:以柱狀圖顯示數(shù)據(jù)")
draw_plot(data)
input('\n按下回車返回菜單')
menu()
elif choice == '3':
print("當前功能:篩選指定列")
keys = list(data[list(data.keys())[0]].keys())
print("當前表格中的列如下:")
num = 1
for key in keys:
print(num, key)
num += 1
choice_col_list = []
while (1):
index_str = input("請選擇需要篩選出的列序號(多列之間用空格分開,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("輸入序號有誤")
continue
if choice_col_list:
break
else:
print("輸入序號有誤")
data = get_specified_cols(data, choice_col_list)
print("篩選成功")
input('\n按下回車返回菜單')
menu()
elif choice == '4':
print("當前功能:篩選指定行")
keys = list(data[list(data.keys())[0]].keys())
print("當前表格中的列如下:")
num = 1
print(num, "城市")
num += 1
for key in keys:
print(num, key)
num += 1
col = int(input("請輸入需要進行篩選的數(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("請輸入比較操作符前的序號:"))-1
operation = op_list[operation]
value = input("請輸入需要篩選的值:")
data = get_specified_data(data, operation, col, value)
print("篩選成功")
input('\n按下回車返回菜單')
menu()
elif choice == '5':
print("當前功能:數(shù)據(jù)排序")
keys = list(data[list(data.keys())[0]].keys())
print("當前表格中的列如下:")
num = 1
for key in keys:
print(num, key) #顯示當前表格中的所有的列
num += 1
col = int(input("請輸入需要進行排序的數(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按下回車返回菜單')
menu()
elif choice == '6':
# 導入文件
files = get_files_name()
data = {}
print("當前文件夾下的文件如下:")
num = 1
for file in files:
print(num, file)
num += 1
while (1):
index_str = input("請選擇需要導入的文件序號(多個文件導入時用空格分開, 輸入0則導入所有文件,輸入多文件則自動合并):")
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("輸入序號有誤")
continue
if choice_file_list:
break
else:
print("輸入序號有誤")
data = load_data(choice_file_list)
print("導入數(shù)據(jù)成功\n")
# 打印菜單
menu()
elif choice == '7':
print("當前功能:保存數(shù)據(jù)")
save(data)
input('\n按下回車返回菜單')
menu()
else:
print("請輸入正確的數(shù)字")
input('\n按下回車返回菜單')
menu()
5.模塊設(shè)計
加載文件夾內(nèi)所有的Excel數(shù)據(jù)
show_data()函數(shù)通過PrettyTable 庫(PrettyTable 庫是python中的一個第三方庫,可用來生成美觀的ASCII格式的表格)將之前保存的字典數(shù)據(jù)生成表格。
#加載顯示數(shù)據(jù)
def show_data(dictory):
try:
keys = list(dictory[list(dictory.keys())[0]].keys())
except:
print("當前數(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)貢獻度分析圖表(以柱狀圖顯示表格數(shù)據(jù))
draw_plot( )函數(shù)使用了matplotlib庫。通過atplotlib.rc( )來設(shè)置字體,通過plt.bar( )函數(shù)來繪制柱狀圖,通過plt.legend( )函數(shù)來給圖添加圖例。
#制作圖表
def draw_plot(dictory):
font = {'family': 'MicroSoft Yahei', 'weight': 'bold', 'size': 7}
matplotlib.rc('font', **font) #設(shè)置中文字體
# 定義三個顏色
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) #通過bar函數(shù)可以用柱狀圖來表達一些變量的統(tǒng)計分布
offset += 1/4
plt.xticks(index, dictory.keys())#表示刻度
plt.legend(cols)#給圖像加上圖例
plt.show()
效果圖

提起Excel表格中指定列數(shù)據(jù)
get_specified_cols()函數(shù)根據(jù)用戶在菜單輸入的列名,通過字典的索引篩選出列名,加載指定列的所有數(shù)據(jù)。
#提起指定列
def get_specified_cols(dictory, col_name_list):
"""
篩選出指定的列
:param dictory:原始字典
:param col_name_list: 需要篩選出的列名,城市名默認出現(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如何實現(xiàn)Excel數(shù)據(jù)讀取和寫入的文章就介紹到這了,更多相關(guān)Python Excel數(shù)據(jù)讀寫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Linux下用Python腳本監(jiān)控目錄變化代碼分享
這篇文章主要介紹了Linux下用Python腳本監(jiān)控目錄變化代碼分享,本文直接給出實現(xiàn)代碼,需要的朋友可以參考下2015-05-05
tensorflow構(gòu)建BP神經(jīng)網(wǎng)絡(luò)的方法
這篇文章主要為大家詳細介紹了tensorflow構(gòu)建BP神經(jīng)網(wǎng)絡(luò)的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03

