python-操作excel
安装xlrd,xlwt
pip install xlrd
pip install xlwt
栗子
读取excel文件
import xlrd wb = xlrd.open_workbook('user_info.xlsx') sheets = wb.sheets() #sheet = sheets[0] #获取第一个sheet sheet = wb.sheet_by_index(0) #获取第一个sheet print(sheet.nrows) #获取行数 print(sheet.ncols) #获取列数 print(sheet.cell_value(0, 1)) #获取指定单元格的值(第0行第1列) print(sheet.row_values(0)) #获取指定行数(0)的所有值 print(sheet.row_values(0, 1, 2)) #获取指定行数的所有值,然后做切片操作
写入excel
#写入excel import xlwt wbook = xlwt.Workbook() wsheet = wbook.add_sheet('user1') wsheet.write(0, 0, 'username') wsheet.write(0, 1, 'password') wbook.save('user.xls')
对excel操作进行封装
opera_excel.py
import xlrd class OperationExcel: """操作excel文件""" def __init__(self, file_path=None, sheet_id=None): if file_path: self.file_path = file_path self.sheet_id = sheet_id else: self.file_path = '../dataconfig/case1.xls' self.sheet_id = 0 self.excel_sheet = self.get_excel_sheet() #获取指定excel中指定的sheet def get_excel_sheet(self): wb = xlrd.open_workbook(self.file_path) sheets = wb.sheets() return sheets[self.sheet_id] #获取excel中指定sheet的行数 def get_sheet_lines(self): lines = self.excel_sheet.nrows return lines #获取指定sheet中一个单元格的内容 def get_cell_value(self, row, col): return self.excel_sheet.cell_value(row, col) if __name__ == '__main__': opera_excel = OperationExcel() print(opera_excel.get_sheet_lines()) print(opera_excel.get_cell_value(2, 2))