Python打开Excel文档并读取数据

Python 版本

目前 Python 3 版本为主流版本,这里测试的版本是:Python 3.10.5。

常用库说明

Python 操作 Excel 的常用库有:xlrd、xlwt、xlutils、openpyxl、pandas。这里主要说明下 Excel 文档 .xls 格式和 .xlsx 格式的文档打开和读取。

Python 操作 .xls 格式的 Excel

参考网址:xlrd --- xlrd 2.0.1 documentationhttps://xlrd.readthedocs.io/en/latest/

python 复制代码
import xlrd

# 定义文件路径并打开文件
filePath = r'C:\Users\mengll\Desktop\测试的EXCEL文档.xls'
file = xlrd.open_workbook(filePath)

# Excel Sheet 页数量:file.nsheets
print("这个表格一共有的sheet数量是: {0}".format(file.nsheets))
# Excel Sheet 页名列表:file.sheet_names()
print("这个表格sheet名是:{0}".format(file.sheet_names()))

# Excel 第一个 Sheet 页:file.sheet_by_index(0)
sheet0 = file.sheet_by_index(0)
# Sheet 页的名称、行数、列数是:sheet.name|sheet.nrows|sheet.ncols
print("{0} {1} {2}".format(sheet0.name, sheet0.nrows, sheet0.ncols))
# Sheet 页指定单元格的值是:sheet.cell_value(rowx=1, colx=1)
print("单元格 A1 内容为:{0}".format(sheet0.cell_value(rowx=0, colx=0)))

# 循环打印 Sheet 的所有行数据
for rx in range(sheet0.nrows):
    print(sheet0.row(rx))

Python 操作 .xlsx 格式的 Excel

参考网址:openpyxl - A Python library to read/write Excel 2010 xlsx/xlsm files --- openpyxl 3.1.3 documentationhttps://openpyxl.readthedocs.io/en/stable/

python 复制代码
import openpyxl

# 定义文件路径并打开文件
filePath = r'C:\Users\mengll\Desktop\测试的EXCEL文档.xlsx'
file = openpyxl.load_workbook(filePath)

# Excel Sheet 页名列表:file.sheetnames
print("这个表格sheet名是:{0}".format(file.sheetnames))
print("这个表格sheet名是:{0}".format(file.worksheets))

# Excel 第一个 Sheet 页:file['sheet0']
sheet = file['sheet0']
# Sheet 页的名称、左上右下单元格、行数、列数是:sheet.title|sheet.dimensions|sheet.max_row|sheet.min_row|sheet.max_column|sheet.min_column
print("{0} {1} {2} {3}".format(sheet.title, sheet.dimensions, sheet.max_row, sheet.max_column))
# Sheet 页指定单元格的值是:sheet.cell(row=1, column=1).value
print("单元格 A1 内容为:{0}".format(sheet.cell(row=1, column=1).value))

工具中其它很多属性和用法,可以参考文档自行尝试,Good Luck~

相关推荐
MO2T21 分钟前
使用 Flask 构建基于 Dify 的企业资金投向与客户分类评估系统
后端·python·语言模型·flask
慢热型网友.24 分钟前
用 Docker 构建你的第一个 Python Flask 程序
python·docker·flask
Naiva24 分钟前
【小技巧】Python + PyCharm 小智AI配置MCP接入点使用说明(内测)( PyInstaller打包成 .exe 可执行文件)
开发语言·python·pycharm
云动雨颤28 分钟前
Python 自动化办公神器|一键转换所有文档为 PDF
运维·python
梅孔立41 分钟前
yum update 报错 Cannot find a valid baseurl for repo: centos-sclo-rh/x86_64 等解决办法
linux·python·centos
前端付豪1 小时前
13、你还在 print 调试🧾?教你写出自己的日志系统
后端·python
这里有鱼汤1 小时前
hvPlot:用你熟悉的 Pandas,画出你没见过的炫图
后端·python
源码站~1 小时前
基于Flask+Vue的豆瓣音乐分析与推荐系统
vue.js·python·flask·毕业设计·毕设·校园·豆瓣音乐
MessiGo1 小时前
Python 爬虫实战 | 国家医保
python
chanalbert2 小时前
Spring 6 源码深度掘金:66+核心原理与高频面试攻坚指南
python·spring·面试