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:網絡文件
轉載于:https://www.cnblogs.com/ashe666/p/8268058.html
總結
以上是生活随笔為你收集整理的Python操作Excel表格的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: nginx+ssl+pm2 部署 nod
- 下一篇: 简单的mysql热备