分享

Python读取Excel文件的方法

 leafcho 2021-02-19

方法一:读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=' ')

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约