Python读取Excel文件的方法

liftword2个月前 (04-01)技术文章24

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

相关文章

一日一技:使用Python读取Excel文件

安装xlrd模块:pip install xlrd使用xlrd模块,可以从电子表格中检索信息。 例如,可以在Python中完成读取,写入或修改数据的操作。 另外,用户可能必须浏览各种工作表并根据某些条...

python怎么读取excel文件

python怎么读取excel文件?1.首先说明我是使用的python3.5,我的office版本是2010,首先打开dos命令窗,安装必须的两个库,命令是:12pip3 install xlrdPi...

详细实例操作:教你用python如何读取和写入EXCEL里面的数据

前言:今天为大家带来的内容是:PYTHON如何读取和写入EXCEL里面的数据,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下,要是喜欢本文内容的朋友记...

python除了熟悉的pandas,openpyxl库也很方便的读取Excel表内容

学习目录了解下电脑中的excel表格文件格式安装openpyxl库使用openpyxl库读取表格内容1 先准备一个表格‘python.xlsx’,表格中包含如下几个sheet页2 导入openpyxl...

Python之Pandas使用系列(八):读写Excel文件的各种技巧

介绍:我们将学习如何使用Python操作Excel文件。我们将概述如何使用Pandas加载xlsx文件以及将电子表格写入Excel。如何将Excel文件读取到Pandas DataFrame:和前面的...