1. openpyxl练习
将以下的excel表中的内容都出来:
读出来的格式为:
每一行数据为一个列表中的值,每一个cell的值是一个字典的值。
[{'user_name': 'agent1', 'pass_word': 'agent1', 'page_title': 'Desktop Layout - xForce'}, {'user_name': 'CosignDoctor1', 'pass_word': 'CosignDoctor1', 'page_title': 'Desktop Layout - xForce'}]
代码:
#-*- coding:utf-8-*- from openpyxl.reader.excel import load_workbook import os class ExcelReader: EXT = "aa" def __init__(self,excel_path,sheet_name): self.wb = load_workbook(excel_path) self.sheet_names = self.wb.get_sheet_names() self.ws = self.wb.get_sheet_by_name(self.sheet_names[0]) self.max_row = self.ws.max_row self.max_col = self.ws.max_column def dic_data(self): if self.max_row < 1: print ("The rows is less than 1") else: data_dict = {} for rx in range(1, self.max_row + 1): temp_list = [] pid = rx w1 = self.ws.cell(row=rx, column=1).value w2 = self.ws.cell(row=rx, column=2).value w3 = self.ws.cell(row=rx,column=3).value temp_list = [w1, w2, w3] data_dict[pid] = temp_list return data_dict def read_dict_data(self): keys = list(map(lambda c: self.ws.cell(row = 1, column = c).value, range(1, self.max_col))) def read_row(r): return dict(map(lambda c: (keys[c - 1], self.ws.cell(row = r, column = c).value), range(1, 1 + len(keys)))) return list(map(read_row, range(2, self.max_row + 1))) if __name__ == "__main__": file_path = os.path.dirname(__file__).split("/Src")[0] + "/ExcelFiles/Test_Login_001.xlsx" sheet_name = "Sheet1" data = ExcelReader(file_path, sheet_name) print (data.read_dict_data())
2. openpyx使用
2.1 在内存中操作workbook,然后创建文件
#-*-coding=utf-8-*- __author__ = 'WJ' from openpyxl import Workbook # 在内存中操作workbook # 在使用openpyxl的时候不需要在本地创建一个文件,直接引入Workbook类就可以直接使用 # 创建一个workbook, 默认有一个sheet wb = Workbook() #可以获取workbook的默认sheet ws = wb.active print (ws) #创建一个sheet ws1 = wb.create_sheet("my_sheet",0) print (ws1) #为sheet设置名字 ws1.title = "my_sheet1" print (ws1) #为sheet tab设置背景颜色 ws1.sheet_properties.tabColor = "1072BA" # 返回所有sheet sheets = wb.sheetnames print (sheets) ################################## #操作数据 # 可以根据cell的位置进入cell,如果该cell有值则会返回值,没有没有值可以直接赋值 ws['A4'] = 4 c = ws['A4'] print (c.value) # 可以根据cell方法为cell赋值 d = ws.cell(row=1,column=1,value=2) # 进入多个cells cell_range = ws['A1':'C2'] #多行或者多列 col_range = ws['C:D'] row_range = ws[5:10] #也可以使用iter_rows()方法 for row in ws.iter_rows(min_row=1,max_col=3,max_row=2): for cell in row: print (cell) #同上可以使用iter_cols()方法 for col in ws.iter_cols(min_row=1,max_col=3,max_row=2): for cell in col: print (cell) #遍历整个文件的行或者列 print ('------------') print (tuple(ws.rows)) #保存到文件 wb.save("D:/test.xlsx")
2.2 对一个已有的excel文件进行操作