excel導(dǎo)出
利用xlwt模塊實(shí)現(xiàn)excel導(dǎo)出功能
這里想封裝起一個(gè)公共的方法,但是發(fā)現(xiàn)字典轉(zhuǎn)列表的順序是無序的,輸出列的數(shù)據(jù)和定義的不一致,這個(gè)問題待解決
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import xlwt
header = ['序號(hào)','姓名','年齡']
data = [
{'id':1,'name':'mike','age':18},
{'id':2,'name':'jack','age':18},
{'id':3,'name':'lina','age':16},
{'id':4,'name':'lnda','age':20},
]
book = xlwt.Workbook(encoding='utf-8', style_compression=0) # 創(chuàng)建一個(gè)Workbook對(duì)象,這就相當(dāng)于創(chuàng)建了一個(gè)Excel文件
sheet = book.add_sheet('test', cell_overwrite_ok=True) # # 其中的test是這張表的名字,cell_overwrite_ok,表示是否可以覆蓋單元格,其實(shí)是Worksheet實(shí)例化的一個(gè)參數(shù),默認(rèn)值是False
# 設(shè)置表頭
i = 0
for k in header:
sheet.write(0, i, k)
i = i + 1
# 數(shù)據(jù)寫入excel
row = 1
for val in data:
print(val)
sheet.write(row, 0, val['id']) # 第二行開始
sheet.write(row , 1, val['name']) # 第二行開始
sheet.write(row , 2, val['age']) # 第二行開始
row = row + 1
# 最后,將以上操作保存到指定的Excel文件中
book.save(r'e:\python\basic\test1.xls') # 在字符串前加r,聲明為raw字符串,這樣就不會(huì)處理其中的轉(zhuǎn)義了。否則,可能會(huì)報(bào)錯(cuò)
excel讀取
利用xlrd模塊實(shí)現(xiàn)excel讀取功能
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import xlrd # 引入xlrd模塊
file = xlrd.open_workbook('test1.xls') # 打開excel文件對(duì)象
table = file.sheets()[0] # 通過索引順序獲取
# table = file.sheet_by_index(0) # 通過索引順序獲取
# table = file.sheet_by_name('test') # 通過表名獲取對(duì)應(yīng)表的數(shù)據(jù)
rows = table.nrows # 總的行數(shù)
columns = table.ncols # 總的列數(shù)
data = [] # 初始化列表
for r in range(1,rows): # 去除表頭所有從第一行開始
rowData = table.row_values(r) # 獲取每一列的數(shù)據(jù)
data.append(rowData) # 追加數(shù)據(jù)到列表中
print(data)