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~

相关推荐
随心点儿27 分钟前
使用python 将多个docx文件合并为一个word
开发语言·python·多个word合并为一个
不学无术の码农30 分钟前
《Effective Python》第十三章 测试与调试——使用 Mock 测试具有复杂依赖的代码
开发语言·python
sleepybear111337 分钟前
在Ubuntu上从零开始编译并运行Home Assistant源码并集成HACS与小米开源的Ha Xiaomi Home
python·智能家居·小米·home assistant·米家·ha xiaomi home
纪伊路上盛名在42 分钟前
(鱼书)深度学习入门1:python入门
人工智能·python·深度学习
夏末蝉未鸣011 小时前
python transformers笔记(TrainingArguments类)
python·自然语言处理·transformer
德育处主任Pro1 小时前
「py数据分析」04如何将 Python 爬取的数据保存为 CSV 文件
数据库·python·数据分析
咸鱼鲸1 小时前
【PyTorch】PyTorch中数据准备工作(AI生成)
人工智能·pytorch·python
遇见你很高兴2 小时前
Pycharm中体验通义灵码来AI辅助编程
python
大虫小呓2 小时前
50个Python处理Excel示例代码,覆盖95%日常使用场景-全网最全
python·excel
大模型真好玩2 小时前
做题王者,实战拉跨!是时候给马斯克的Grok4泼盆冷水了!(Grok 4模型详细测评报告)
人工智能·python·mcp