python 读取excel文件
def readexcel(file,sheet_index=0):
#parameters:file:文件路径
#sheet_index: 读取的工作表索引
#return:二维数组
workbook = xlrd.open_workbook(file)
# all_sheets_list = workbook.sheet_names()
# print("本文件中所有的工作表名称:", all_sheets_list)
# 按索引读取工作表
sheet = workbook.sheet_by_index(sheet_index)
print("工作表名称:", sheet.name)
print("行数:", sheet.nrows)
print("列数:", sheet.ncols)
# 按工作表名称读取数据
# second_sheet = workbook.sheet_by_name("b")
# print("Second sheet Rows:", second_sheet.nrows)
# print("Second sheet Cols:", second_sheet.ncols)
# 获取单元格的数据
# cell_value = sheet.cell(1, 0).value
# print("获取第2行第1列的单元格数据:", cell_value)
data = []
for i in range(0, sheet.nrows):
data.append(sheet.row_values(i))
return data
调用函数:
readexcel('C:\Users\qsl\Desktop\a.xlsx')
居然报错:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
解决方案:—路径问题
①readexcel('C:\\Users\\qsl\\Desktop\\a.xlsx')
②readexcel(r'C:\Users\qsl\Desktop\a.xlsx')