目的:实现用python的另一种方法做excel的读取、新增操作。
环境:ubuntu 16.04 Python 3.5.2
情景:之前介绍了一种操作excel文件的方法(私链),现在使用另一种方法读写excel文件,一次性读出或写入,读写也很方便,读出为有序字典,像二维数组,需要用到3个第三方模块,pyexcel-io, pyexcel-xls, xlrd,主要导入pyexcel-xls和collections,pyexcel-xls基于xlrd和pyexcel-io,所以支持xls和xlsx。
表格的读取:
读取需要导入pyexcel-xls和collections模块:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
from
collections
import
OrderedDict
from
pyexcel_xls
import
get_data
# open xlsx
def
read_xls():
_xls_data
=
get_data(r
'abc.xlsx'
)
for
n
in
_xls_data.keys():
print
(
'%s is %s'
%
(n, _xls_data[n]))
print
(_xls_data)
if
__name__
=
=
'__main__'
:
read_xls()
|
这个模块把整个表格转换为OrderedDict(有序字典),每个key就是它的子表名,而value值则是表的内容,以二层列表显示,类似二维数组。
表格的写入基于xlwt,也不支持xlsx格式。
表格的写入:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
from
collections
import
OrderedDict
from
pyexcel_xls
import
save_data
# save xls file
def
save_xls():
_data
=
OrderedDict()
_table
=
[]
_row_1
=
[
'ID'
,
'NAME'
,
'LEVEL'
,
'money'
]
_row_2
=
[
'3'
,
'red'
,
'5'
,
'3000'
]
_table.append(_row_1)
_table.append(_row_2)
_data.update({
'test'
:_table})
save_data(
'abb.xls'
, _data)
if
__name__
=
=
'__main__'
:
save_xls()
|
在数据的一次性写入和一次性读取时,用这个方法很方便,如果是针对性处理,可以使用方法一(私链)。
本文转自RickyHuL51CTO博客,原文链接:http://blog.51cto.com/rickyh/1955637 ,如需转载请自行联系原作者