200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > python读取excel(读写处理xls或xlsx)

python读取excel(读写处理xls或xlsx)

时间:2022-04-10 21:44:17

相关推荐

python读取excel(读写处理xls或xlsx)

前言

在很多应用场景中,程序都需要读取excel的配置。

比如,在游戏中,数值策划用excel 建好了数值表,我们要导入到游戏中。比如最简单的,等级-经验表。

注: 本文更新于.4.12, 基于python3, 以及扩展模块:pyexcel-xlsx

安装:

pip install pyexcel-xlsx

读Excel表,xlsx格式:

数据示例:

python 代码示例:

import jsonfrom pyexcel_xlsx import get_datadata = get_data("d:/lv.xlsx")print(type(data))# 可以看到, 类型为collections.OrderedDictprint(json.dumps(data))

看一下输出, 是可以读出来的:

<class 'collections.OrderedDict'>

{"Sheet1": [["\u7b49\u7ea7", "\u5347\u7ea7\u9700\u8981\u7ecf\u9a8c"], [1, 40], [2, 90], [3, 140], [4, 210], [5, 280], [6, 360], [7, 450], [8, 540], [9, 650], [10, 760]], "Sheet2": [], "Sheet3": []}

--------- 以下是旧的, python2版本的文章 ---------

概述

这里我使用了 pyexcel-xls 这个东西。我个人觉得这个东西导出的数据结构,结构可读性很强,数据结构如下:

整个excel文件,转化为一个字典结构:每个key就是一个子表(Sheet)

每个子表(Sheet),转化为一个二维数组:分别为行和列。

注意,本文对应的版本更新为 pyexcel-xls 0.2.3。

安装

pypi 的地址:

/pypi/pyexcel-xls/

■ 方法一:

可以直接用pip安装

pip install pyexcel-xls

■ 方法二:

下载安装包手动安装。

先安装两个依赖包:

xlrdpyexcel-io

然后再安装pyexcel-xls

使用

一、读excel数据 (xls, xlsx)

1,先建立一个目标excel表,这里为了做演示,简单建立一个 read_test.xlsx 文件:

里面的数据(3行,4列):

2,写Python 脚本,读这个文件:

#! /usr/bin/env python#coding=utf-8# pyexcel_xls 以 OrderedDict 结构处理数据from collections import OrderedDictfrom pyexcel_xls import get_datafrom pyexcel_xls import save_datadef read_xls_file():xls_data = get_data(r"D:\read_test.xlsx")print "Get data type:", type(xls_data)for sheet_n in xls_data.keys():print sheet_n, ":", xls_data[sheet_n]if __name__ == '__main__':read_xls_file()

看一下输出的打印信息:

可以看到:

整个excel文件,转化为一个OrderedDict (有序字典)结构:每个key就是一个子表(Sheet)。

每个子表(Sheet),转化为一个列表结构:很像二维数组,第一层列表为行(Row),行的下标为列(Column),对应的值为单元格的值。编码为 unicode

简单,易用,读出数据后,非常适合做二次处理!

■ 注意,excel文件名(就是那个xls或者xlsx文件),尽量不要用中文,如果您要使用中文,请转化为unicode编码,如:

xls_data = get_data(unicode(r"D:\试试.xlsx", "utf-8"))

二、写excel数据 (xls)

根据上文,写也比较简单,不做过多解释。

#! /usr/bin/env python#coding=utf-8# pyexcel_xls 以 OrderedDict 结构处理数据from collections import OrderedDictfrom pyexcel_xls import get_datafrom pyexcel_xls import save_datadef read_xls_file():xls_data = get_data(unicode(r"D:\试试.xlsx", "utf-8"))print "Get data type:", type(xls_data)for sheet_n in xls_data.keys():print sheet_n, ":", xls_data[sheet_n]return xls_data# 写Excel数据, xls格式def save_xls_file():data = OrderedDict()# sheet表的数据sheet_1 = []row_1_data = [u"ID", u"昵称", u"等级"] # 每一行的数据row_2_data = [4, 5, 6]# 逐条添加数据sheet_1.append(row_1_data)sheet_1.append(row_2_data)# 添加sheet表data.update({u"这是XX表": sheet_1})# 保存成xls文件save_data("D:\write_test.xls", data)if __name__ == '__main__':save_xls_file()

看一下写出的xls文件:

好,数据读写完成!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。