python3字典写入excel_python3:excel操作之读取数据并返回字典 + 写入的案例
excel寫入數(shù)據(jù),使用openpyxl庫
class WriteExcel:
def __init__(self,path):
self.path = path
def write_excel(self, sheet_name, content):
"""
在excel指定sheet中的寫入指定內(nèi)容,以追加方式
:return:
"""
wb = openpyxl.load_workbook(self.path)
ws = wb[sheet_name]
# 獲取最大行
row_num = ws.max_row
try:
ws.cell(row=row_num+1, column=1).value = content
except Exception as msg:
print('寫入excel失敗:', msg)
finally:
wb.save(self.path)
if __name__ == '__main__':
WE = WriteExcel('../config/data.xlsx')
WE.write_excel(sheet_name='user', content='瑟瑟發(fā)抖')
excel讀取數(shù)據(jù),使用xlrd庫
class ReadExcel:
def __init__(self,path):
self.path = path
def read_excel(self,row):
"""
遍歷excel所有sheet,并以字典返回
:param row:
:return:
"""
with xlrd.open_workbook(self.path, 'rb') as book:
sheets = book.sheet_names() # 找到所有sheets
data_dict = {}
for sheet in sheets:
table = book.sheet_by_name(sheet) # 找到要操作的sheet
# 獲取sheet所有列數(shù)
col_num = table.ncols
# 讀取第一行的值,作為每個(gè)sheet返回字典的key
keys = table.row_values(0)
# 讀取除指定行,作為每個(gè)sheet返回字典的value
values = table.row_values(row)
# 遍歷所有列,并以字典接收,其中第一行作為字典的key,其他行作為字典的value
sheet_dict = {}
for col in range(col_num):
sheet_dict[keys[col]] = values[col]
# 遍歷所有sheet,并以字典接收返回,其中sheet名稱作為字典的key,每個(gè)sheet的數(shù)據(jù)作為字典的value
data_dict[sheet] = sheet_dict
return data_dict
讀取結(jié)果:
補(bǔ)充知識(shí):Python+selenium+ddt數(shù)據(jù)驅(qū)動(dòng)測(cè)試
我就廢話不多說了,大家還是直接看代碼吧~
import ddt
testData = ['1','2','3']
print testData
@ddt.ddt
class Bolg(unittest.TestCase):
def setUp(self):
print('setUp')
@ddt.data(*testData)
def test_l(self, data):
print(data)
def tearDown(self):
print('tearDown')
if __name__ == "__main__":
unittest.main()
============
1
2
3
以上這篇python3:excel操作之讀取數(shù)據(jù)并返回字典 + 寫入的案例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持隨便開發(fā)網(wǎng)。
總結(jié)
以上是生活随笔為你收集整理的python3字典写入excel_python3:excel操作之读取数据并返回字典 + 写入的案例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Win7系统电脑待机断网怎么解决 电脑一
- 下一篇: python遥感影像分类代码_pytho