博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python openpyxl解析Excel
阅读量:4656 次
发布时间:2019-06-09

本文共 2783 字,大约阅读时间需要 9 分钟。

在工作中,需要使用到Excel的地方非常多,很多公司会用Excel来维护测试用例,如果需要做接口测试,那么解析Excel是不可少的了,下面是自己对Excel的方法进行封装了一下,基本上可以满足对Excel的操作,如下:

1 # -*- coding: UTF-8 -*- 2 from openpyxl import load_workbook 3 from openpyxl.styles import Font,Border,Side 4 import time  5  6  7 class ParseExcel(object): 8  9     def __init__(self,excel_file_path):10         self.excel_file_path = excel_file_path11         self.workbook = load_workbook(self.excel_file_path)12         self.font = Font(color=None)13         self.colorDict = {
"red": 'FFFF3030', "green": 'FF008B00'}14 self.sheet = self.workbook.active15 16 def get_default_name(self):17 return self.sheet.title18 19 def get_sheet_by_name(self,sheet_name):20 #因为get_sheet_by_name就是获取sheet,如果加上self.sheet,就相当于set了21 sheet = self.workbook.get_sheet_by_name(sheet_name)22 return sheet23 24 def get_sheet_by_index(self,sheet_index):25 sheet_name = self.workbook.get_sheet_names()[sheet_index]26 sheet = self.get_sheet_by_name(sheet_name)27 return sheet28 29 def set_sheet_by_name(self,sheet_name):30 self.sheet = self.get_sheet_by_name(sheet_name)31 32 def set_sheet_by_index(self,sheet_index):33 self.sheet = self.get_sheet_by_index(sheet_index)34 35 def get_min_row_no(self):36 return self.sheet.min_row37 38 def get_min_col_no(self):39 return self.sheet.min_column40 41 def get_max_col_no(self):42 return self.sheet.max_column43 44 def get_max_row_no(self):45 return self.sheet.max_row46 47 def get_all_rows(self):48 rows = []49 for row in self.sheet.iter_rows():50 rows.append(row)51 return rows52 53 def get_all_cols(self):54 cols = []55 for col in self.sheet.columns:56 cols.append(col)57 return cols58 59 def get_single_row(self,row_no):60 #此处的row的值是从0开始的61 return self.get_all_rows()[row_no]62 63 def get_single_col(self,col_no):64 return self.get_all_cols()[col_no]65 66 def get_cell_content(self,row_no,col_no):67 #再用cell函数时,要指定参数,要写上row = xxx,不然容易报错,因为第一个参数不是行或列68 content = self.sheet.cell(row=row_no,column=col_no)69 return content70 71 def get_cell(self,row_no,col_no):72 return self.sheet.cell(row=row_no,column=col_no)73 74 def write_cell_time(self,row_no,col_no):75 self.sheet.cell(row=row_no,column=col_no).value = time.now()76 77 def write_cell_content(self,row_no,col_no,content,font=None):78 #此处row和column是从1开始的79 self.sheet.cell(row = row_no,column = col_no).value = content80 81 def save_excel_file(self):82 self.workbook.save(self.excel_file_path)

 

转载于:https://www.cnblogs.com/bettywang/p/9332289.html

你可能感兴趣的文章