码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习笔记16—电子表格

时间:2016-09-22 11:27:57      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

openpyl 模块是解决 Microsoft Excel 2007/2010 之类版本中扩展名是 Excel 2010 xlsx/xlsm/xltx/xltm 的文件的读写的第三方库。

安装

pip install openpyxl

workbook 和 sheet的建立

引入模块

>>> from openpyxl import Workbook

建立工作薄

>>> wb = Workbook()

建立sheet

>>> ws = wb.active

另外还可以在这个sheet后面追加

>>> ws1 = wb.create_sheet()

给sheet重命名

>>> ws.title = "Python"

此时,可以使用下面的方式从工作簿对象中得到 sheet

>>> ws01 = wb[Python] #sheet 和工作簿的关系,类似键值对的关系
>>> ws is ws01
True

显示所有的sheet

>>> print wb.get_sheet_names()
[uPython, Sheet1, Sheet2]

也可以用循环语句,把所有的 sheet 名字打印出来。

>>> for sh in wb:
...  print sh.title
... 
Python
Sheet1
Sheet2

cell

为了能够清楚理解填数据的过程,将电子表中约定的名称以下图方式说明:
技术分享

对于 sheet,其中的 cell 是它的下级单位。所以,要得到某个 cell,可以这样:

>>> b4 = ws[B4]

这样

>>> a5 = ws.cell("A5")

还有这样

>>> a2 = ws.cell(row = 2, column = 1)

 

如果要给 B4 添加数据,可以这么做:

>>> ws[B4] = 4444

因为 b4 引用了一个 cell 对象,所以可以利用这个对象的属性来查看其值:

>>> b4.value
4444

 

一次创建多个cell
>>> cells = ws["A1":"C3"]
>>> tuple(ws.iter_rows("A1:C3"))    #查看
((<Cell Python.A1>, <Cell Python.B1>, <Cell Python.C1>), (<Cell Python.A2>, <Cell Python.B2>, <Cell Python.C2>), (<Cell Python.A3>, <Cell Python.B3>, <Cell Python.C3>))

还可以用下面的循环方法,一个一个地读到每个cell 对象:

IndentationError: expected an indented block
>>> for row in ws.iter_rows("A1:C3"):
...   for cell in row:
...      print cell
... 
<Cell Python.A1>
<Cell Python.B1>
<Cell Python.C1>
<Cell Python.A2>
<Cell Python.B2>
<Cell Python.C2>
<Cell Python.A3>
<Cell Python.B3>
<Cell Python.C3>

给这些cell赋值

>>> i = 1
>>> for row in ws.rows:
...      for cell in row:
...         cell.value = i
...         i += 1
... 

查看添加的数据

>>> for col in ws.columns:
...   for cell in col:
...     print cell.value
... 
1
4
7
10
13
2
5
8
11
14
3
6
9
12
15


保存

>>> wb.save("demo.xlsx")

 

查看工作薄

技术分享

 

读取已有的电子表格

>>> from openpyxl import load_workbook
>>> wb2 = load_workbook("demo.xlsx")
>>> print wb2.get_sheet_names()
[uPython, uSheet1, uSheet2]
>>> ws_wb2 = wb2["Python"]
>>> for row in ws_wb2.rows:
...   for cell in row:
...     print cell.value
... 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

 

 

其它第三方库

针对电子表格的第三方库,除了上面这个 openpyxl 之外,还有别的,列出几个,供参考,使用方法大同小异。
• xlsxwriter:针对 Excel 2010 格式,如 .xlsx,官方网站:https://xlsxwriter.readthedocs.org/,这个官方文档写的图文并茂。非常好读。
下面两个用来处理 .xls 格式的电子表表格。
• xlrd:网络文件:https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html?p=4966
• xlwt:网络文件:http://xlwt.readthedocs.org/en/latest/

 

Python学习笔记16—电子表格

标签:

原文地址:http://www.cnblogs.com/zydev/p/5895405.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!