方法一:读excel文件单元格数据 import xlrd book = xlrd.open_workbook('fruit.xlsx') print('sheet页名称:',book.sheet_names()) sheet = book.sheet_by_index(0) rows = sheet.nrows cols = sheet.ncols print('该工作表有%d行,%d列.'%(rows,cols)) print('第三行内容为:',sheet.row_values(2)) print('第二列内容为%s,数据类型为%s.'%(sheet.col_values(1),type(sheet.col_values(1)))) print('第二列内容为%s,数据类型为%s.'%(sheet.col(1),type(sheet.col(1)))) print('第二行第二列的单元格内容为:',sheet.cell_value(1,1)) print('第三行第二列的单元格内容为:',sheet.cell(2,1).value) print('第五行第三列的单元格内容为:',sheet.row(4)[2].value) print('第五行第三列的单元格内容为%s,数据类型为%s'%(sheet.col(2)[4].value,type(sheet.col(2)[4].value))) print('第五行第三列的单元格内容为%s,数据类型为%s'%(sheet.col(2)[4],type(sheet.col(2)[4]))) 方法二:读excel文件单元格数据--openpyxl import openpyxl book = openpyxl.load_workbook('fruit.xlsx') print('所有sheet页名称:',book.sheetnames) sheet = book.worksheets[0] sheet2 = book['Sheet1'] sheet3 = book[book.sheetnames[0]] print('工作表名称:',sheet3.title) rows = sheet.max_row cols = sheet.max_column print('该工作表有%d行,%d列.'%(rows,cols)) print('该工作表的的第三行第二列的单元格内容为:%.2f',(sheet.cell(3,2).value)) 以下为行列生成器 print(sheet.rows,sheet.columns) for col in sheet.columns: print(col) for row in sheet.rows: for i in row: print(i.value,end=' ') print() 获取某一行或列的内容 for i in list(sheet.rows)[1]: print(i.value,end=' ') print() for i in list(sheet.columns)[0]: print(i.value,end=' ') |
|