Python读取和写入Excel数据


Posted in Python onApril 20, 2022

1. 功能分析

1.加载文件夹内所有的Excel数据;

2.生产贡献度分析图表(以柱状图显示表格数据);

3.提起Excel表格中指定列数据;

4.定向筛选所需数据;

5.多表数据统计排行;

6.多表数据合并新excel文件。

2.系统开发环境

Anaconda3,在conda 中,window和ubuntu中的python功能一样 。

pycharm。

3.安装依赖库

Python读取和写入Excel数据

这些依赖包   都要装好

import os
import xlrd2 #xlrd: 对Excel进行读相关操作
import xlwt #xlwt: 对Excel进行写相关操作,且只能创建一个全新的Excel然后进行写入和保存。
import numpy
import matplotlib
from prettytable import PrettyTable  #PrettyTable 是python中的一个第三方库,可用来生成美观的ASCII格式的表格
from matplotlib import pyplot as plt

4. 主函数设计

Excel数据分析师的主函数main(),主要用于实现系统的主界面。在主函数main()中,首先调用get_files_name()函数获取文件名。

get_files_name()函数代码如下:

#导入文件
def get_files_name():
    """
    用于获取文件名
    :return: 返回值为文件名组成的列表
    """
    file_list = os.listdir('./data')
    return file_list

然后调用load_data()函数来读取excel文件并字典方式保存。

#保存生产excel表
def load_data(file_list):
    """
    用于读取指定的文件并保存至字典数据结构中
    :param file_list: 需要加载的文件列表
    :return: 保存了文件内容的字典
    """
    dictory = {}
    for file in file_list:
        # 获取表格文件
        book = xlrd2.open_workbook('./data/'+file)
        # 获取表格中的所有sheet
        names = book.sheet_names()
        # 获取第一个sheet
        sheet = book.sheet_by_index(0)
        # 获取当前表格的行数
        rows = sheet.nrows
        # 获取当前表格的列数
        cols = sheet.ncols
        # 获取表头文件,即表格第一行
        head = sheet.row_values(0)
        for row in range(rows-1):
            # 如果当前字典中没有该城市则创建一个
            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

接着调用menu()函数生成功能选择菜单。

menu()函数代码如下: 

# 打印菜单
def menu():
    print("  ----------Excel 数据分析师----------")
    print("{:<30}".format("  ==============功能菜单============== "))
    print("{:<30}".format("   1. 显示当前数据                     "))
    print("{:<30}".format("   2. 以柱状图展示当前数据              "))
    print("{:<30}".format("   3. 提起指定列                       "))
    print("{:<30}".format("   4. 定向筛选指定元素                       "))
    print("{:<30}".format("   5. 数据排行                         "))
    print("{:<30}".format("   6. 重新加载数据                      "))
    print("{:<30}".format("   7. 保存当前数据                      "))
    print("{:<30}".format("   0. 退出程序                          "))
    print("{:<30}".format(" ==================================== "))
    print("{:<30}".format(" 说明:输入相应数字后按下回车选择指定功能 "))
    print('\n')

并且应用if语句控制各个子函数的调用,从而实现对Excel文件的选择,Excel数据的加载,选择、筛选、合并、排序和统计等功能。

主函数完整代码如下:

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("导入数据成功\n")
    # 调用函数,打印菜单
    menu()
    while 1:
        choice = input("请选择指定功能:")
        if choice == '0':
            print("\n退出程序\n")
            exit()
        elif choice == '1':
            print("当前功能:显示当前数据")
            show_data(data)
            input('\n按下回车返回菜单')
            menu()
        elif choice == '2':
            print("当前功能:以柱状图显示数据")
            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("请输入需要进行筛选的数据所在的列:"))-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("当前功能:数据排序")
            keys = list(data[list(data.keys())[0]].keys())
            print("当前表格中的列如下:")
            num = 1
            for key in keys:
                print(num, key) #显示当前表格中的所有的列
                num += 1
            col = int(input("请输入需要进行排序的数据所在的列:")) - 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("导入数据成功\n")
            # 打印菜单
            menu()
        elif choice == '7':
            print("当前功能:保存数据")
            save(data)
            input('\n按下回车返回菜单')
            menu()
        else:
            print("请输入正确的数字")
            input('\n按下回车返回菜单')
            menu()

5.模块设计

加载文件夹内所有的Excel数据

show_data()函数通过PrettyTable 库(PrettyTable 库是python中的一个第三方库,可用来生成美观的ASCII格式的表格)将之前保存的字典数据生成表格。

#加载显示数据
def show_data(dictory):
    try:
        keys = list(dictory[list(dictory.keys())[0]].keys())
    except:
        print("当前数据为空")
        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)

效果图如下:

Python读取和写入Excel数据

生产贡献度分析图表(以柱状图显示表格数据)

draw_plot( )函数使用了matplotlib库。通过atplotlib.rc( )来设置字体,通过plt.bar( )函数来绘制柱状图,通过plt.legend( )函数来给图添加图例。

#制作图表
def draw_plot(dictory):
    font = {'family': 'MicroSoft Yahei', 'weight': 'bold', 'size': 7}
    matplotlib.rc('font', **font) #设置中文字体
    # 定义三个颜色
    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函数可以用柱状图来表达一些变量的统计分布
        offset += 1/4
    plt.xticks(index, dictory.keys())#表示刻度
    plt.legend(cols)#给图像加上图例
    plt.show()

效果图 

Python读取和写入Excel数据

提起Excel表格中指定列数据

get_specified_cols()函数根据用户在菜单输入的列名,通过字典的索引筛选出列名,加载指定列的所有数据。

#提起指定列
def get_specified_cols(dictory, col_name_list):
    """
    筛选出指定的列
    :param dictory:原始字典
    :param col_name_list: 需要筛选出的列名,城市名默认出现
    :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

效果图如下:

Python读取和写入Excel数据

到此这篇关于详解Python如何实现Excel数据读取和写入的文章就介绍到这了!

Python 相关文章推荐
Python中%r和%s的详解及区别
Mar 16 Python
Python编程之字符串模板(Template)用法实例分析
Jul 22 Python
python 简单搭建阻塞式单进程,多进程,多线程服务的实例
Nov 01 Python
python3.6使用pickle序列化class的方法
Oct 22 Python
Python图像处理之颜色的定义与使用分析
Jan 03 Python
pycharm的console输入实现换行的方法
Jan 16 Python
Python实现查找字符串数组最长公共前缀示例
Mar 27 Python
Python中使用pypdf2合并、分割、加密pdf文件的代码详解
May 21 Python
Python虚拟环境的原理及使用详解
Jul 02 Python
Python PyCharm如何进行断点调试
Jul 05 Python
Python flask框架端口失效解决方案
Jun 04 Python
pycharm安装深度学习pytorch的d2l包失败问题解决
Mar 25 Python
Python 的演示平台支持 WSGI 接口的应用
Apr 20 #Python
python​格式化字符串
Apr 20 #Python
Python编写冷笑话生成器
Apr 20 #Python
Python Django / Flask如何使用Elasticsearch
Apr 19 #Python
python中mongodb包操作数据库
Apr 19 #Python
Elasticsearch 聚合查询和排序
Apr 19 #Python
Elasticsearch 基本查询和组合查询
Apr 19 #Python
You might like
PHP 生成的XML以FLASH获取为乱码终极解决
2009/08/07 PHP
Memcache 在PHP中的使用技巧
2010/02/08 PHP
php 自写函数代码 获取关键字 去超链接
2010/02/08 PHP
基于php冒泡排序算法的深入理解
2013/06/09 PHP
php实现图形显示Ip地址的代码及注释
2014/01/20 PHP
Yii2中hasOne、hasMany及多对多关联查询的用法详解
2017/02/15 PHP
Yii框架多语言站点配置方法分析【中文/英文切换站点】
2020/04/07 PHP
使用javascript实现Iframe自适应高度
2014/12/24 Javascript
jQuery中each()方法用法实例
2014/12/27 Javascript
微信小程序购物商城系统开发系列-工具篇的介绍
2016/11/21 Javascript
Javascript中常用类型的格式化方法小结
2016/12/26 Javascript
Node.js事件的正确使用方法
2019/04/05 Javascript
微信小程序bindinput与bindsubmit的区别实例分析
2019/04/17 Javascript
javascript异步编程的六种方式总结
2019/05/17 Javascript
[49:35]KG vs SECRET 2019国际邀请赛小组赛 BO2 第一场 8.16
2019/08/19 DOTA
使用Python的Supervisor进行进程监控以及自动启动
2014/05/29 Python
python将字典内容存入mysql实例代码
2018/01/18 Python
利用Python在一个文件的头部插入数据的实例
2018/05/02 Python
Python实现的根据IP地址计算子网掩码位数功能示例
2018/05/23 Python
Python读取csv文件分隔符设置方法
2019/01/14 Python
python如何给字典的键对应的值为字典项的字典赋值
2019/07/05 Python
关于pycharm中pip版本10.0无法使用的解决办法
2019/10/10 Python
django-xadmin根据当前登录用户动态设置表单字段默认值方式
2020/03/13 Python
CSS3 对过渡(transition)进行调速以及延时
2020/10/21 HTML / CSS
HTML5使用drawImage()方法绘制图像
2014/06/23 HTML / CSS
html5调用app分享功能示例(WebViewJavascriptBridge)
2018/03/21 HTML / CSS
美国休闲服装品牌:J.Crew Factory
2017/03/04 全球购物
美国咖啡批发网站:Coffee.org
2017/06/29 全球购物
教育系毕业生中文求职信范文
2013/10/06 职场文书
数控专业毕业生自荐信范文
2014/03/04 职场文书
经典婚礼主持词
2014/03/13 职场文书
学术会议主持词
2014/03/17 职场文书
企业法人授权委托书
2014/04/03 职场文书
给校长的建议书200字
2014/05/16 职场文书
2015大学生入党个人自传
2015/06/26 职场文书
2016年优秀共产党员先进事迹材料
2016/02/29 职场文书