pip install xlrdpython
pip install xlwtspa
栗子excel
讀取excel文件code
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)) #獲取指定行數的全部值,而後作切片操做
寫入excelblog
#寫入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')
opera_excel.pyip
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))