python3:excel操作之读取数据并返回字典操作之读取数据并返回字典 + 写入的案例写入的案例
主要介绍了python3:excel操作之读取数据并返回字典 + 写入的案例,具有很好的参考价值,希望对大家有所帮
助。一起跟随小编过来看看吧
excel写入数据,使用openpyxl库
class WriteExcel:
def __init__(self,path):
self.path = path
def write_excel(self, sheet_name, content):
"""
在excel指定sheet中的写入指定内容,以追加方式
: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='瑟瑟发抖')
excel读取数据,使用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
评论0