Python操作Excel表格
一、安装
安装openpyxl模块
sudo pip install openpyxl
二、workbook和sheet
#引入模块
from openpyxl import Workbook
---------实例化Workbook类展开工作
wb=Workbook()
---------新建sheet
#在当前工作簿新建一个sheet并且是当前使用的
ws=wb.active
#在sheet后面追加
ws1=wb.create_sheet()
#还可以插队
ws2=wb.create_sheet(1) //在第二个位置插入sheet
----------给sheet命名
ws.title="python"
----------获取sheet对象
#此时你可以使用下面的方式从工作簿对象中得到sheet
ws01=wb['python']
ws is ws01 //True
#或者这种方式:
ws02=wb.get_sheet_by_name("python")
ws01 is ws02 //True
---------显示所有sheet
wb.get_sheet_names() #显示所有sheet
三、cell
---------填写数据之获取(创建)cell
b4=ws['B4'] //如果B4这个cell已经有了就是获取B4的值没有则创建
a1=ws.cell("A1") //有的获取,无的创建
a2=ws.cell(row=2,column=1) //有的获取,无的创建
cells=ws["A1":"C3"] //切片方式创建多个cell
----------填写数据
ws['A2']="This A2's value" //
a2=ws.cell("A2") a2.value="This A2's value"
----------查看创建结果
tuple(ws.iter_rows()) //return all cells
tuple(ws.iter_rows("A1":"C3")) //return area's cells
((<Cell u'python'.A1>, <Cell u'python'.B1>, <Cell u'python'.C1>),
(<Cell u'python'.A2>, <Cell u'python'.B2>, <Cell u'python'.C2>),
(<Cell u'python'.A3>, <Cell u'python'.B3>, <Cell u'python'.C3>))
---row(行)column(列)
-------tuple(ws.rows) #以行排序
((<Cell u'python'.A1>, <Cell u'python'.B1>, <Cell u'python'.C1>),
(<Cell u'python'.A2>, <Cell u'python'.B2>, <Cell u'python'.C2>),
(<Cell u'python'.A3>, <Cell u'python'.B3>, <Cell u'python'.C3>))
--------tuple(ws.columns) #以列排序
((<Cell u'python'.A1>, <Cell u'python'.A2>, <Cell u'python'.A3>),
(<Cell u'python'.B1>, <Cell u'python'.B2>, <Cell u'python'.B3>),
(<Cell u'python'.C1>, <Cell u'python'.C2>, <Cell u'python'.C3>))
-------------批量赋值
i=1
for row in ws.rows:
for cell in row:
cell.value=i
i +=1
------tuple(ws.values)
((1, 2, 3), (4, 5, 6), (7, 8, 9))
四、保存数据
wb.save("excel.xlsx")
五、读取已有文件
from openpyxl import load_workbook
wb2=load_workbook("excel.xlsx")
print wb2.get_sheet_names()
sheet_u=wb2['python']
tuple(sheet_u.values)
#((1L, 2L, 3L), (4L, 5L, 6L), (7L, 8L, 9L))
-----for循环获取
for row in ws.rows:
for cell in row:
print cell.value
1,2,3,4,5,6,7,8,9
安装第三方库
xlsxwriter:针对Excel 2010格式
xlrd:网络文件
xlwt:网络文件