Python 读取整个excel数据,指定行数据和指定列数据解决方法
import xlrd
class operateExcel(object):
def __init__(self, filepath="../user_list_命名格式.xls", sheet_name="users"):
self.filepath = filepath # excel所在路径
self.sheet_name = sheet_name # excel中sheet页的名字
self.data = xlrd.open_workbook(self.filepath)
self.table = self.data.sheet_by_name(self.sheet_name) #获取数据对象
self.rows = self.table.nrows # 获取excel所有有效行
self.cols = self.table.ncols # 获取excel所有有效列
self.table_header = self.table.row_values(0) # 获取指定sheet中的表头
# 读取表格中所有的数据
def read_all_excel(self):
datas = []
for i in range(1, self.rows):
sheet_data = {}
for j in range(self.cols):
# 获取单元格数据
c_cell = self.table.cell(i, j)
sheet_data[self.table_header[j]] = c_cell
datas.append(sheet_data)
return datas
# 读取表格中指定列数据
def read_special_col_data(self, col=0):
datas = []
for i in range(1, self.rows):
c_cell = self.table.cell(i, col)
tmp_data = c_cell
datas.append(tmp_data)
return datas
# 读取表格中指定行的数据
def read_special_row_data(self, row=0):
for i in range(1, self.rows):
row_data = self.table.row_values(row)
return row_data
if __name__ == "__main__":
print(operateExcel().read_all_excel()) # 读取整个表格的数据
print(operateExcel().read_special_col_data(col=2)) # 读取excel第二列数据
print(operateExcel().read_special_row_data(row=1)) # 读取excel第一行数据
来源:专注测试领域