Python 读写 Excel 文件库推荐和使用教程

文章目录

    • 前言
    • [Python 读写 Excel 库简介](#Python 读写 Excel 库简介)
    • [openpyxl 处理 Excel 文件教程](#openpyxl 处理 Excel 文件教程)
    • [pandas 处理 Excel 文件教程](#pandas 处理 Excel 文件教程)
    • 总结

前言

Python 读写 Excel 文件的库总体看还是很多的, 各有其优缺点, 以下用一图总结各库的优缺点, 同时对整体友好的库重点介绍其使用教程。

Python 读写 Excel 库简介

库名称 .xls .xlsx 读取 写入 修改 保存 格式调整 插入图片
xlrd × × × × ×
xlwt × ×
xlutils × × × ×
xlwings
XlsxWriter × × ×
openpyxl ×
pandas × × ×

注: openpyxl: 优点是不依赖Excel,计算机上不安装Excel它也能读写Excel文件,所以适合做开发。

openpyxl 处理 Excel 文件教程

python 复制代码
import openpyxl


def learn_openpyxl_deal_excel(fileName):
    # https://openpyxl.readthedocs.io/en/stable/index.html
    # 1 读取文件
    wb = openpyxl.load_workbook(fileName)
    sheet = wb['Sheet1']
    for sheet in wb:  # 遍历所有 sheet
        print(sheet.title)
    print(wb.sheetnames)

    # 2 获取单元格值
    # 1) 指定坐标范围的值
    cellss = sheet['A1:B5']
    # 2) 指定列的值
    cells = sheet['A']
    cellss = sheet['A:C']
    # 3) 指定行的值
    cells = sheet[5]
    cellss = sheet[5:7]
    # 4) 获取单元格的值 # 行下标从 1 开始 列下标从 0 开始
    print(sheet[1][0].value)
    # for cells in cellss:
        # for cell in cells:
            # print(cell.value)

    # 3 写入数据
    cell = sheet['D4']
    cell.value = '521'
    sheet.cell(1, 1).value = "write_Data"

    # 4 保存文件
    wb.save('data/new_data_openpyxl.xlsx')

    # 5 新建文件
    workbook = openpyxl.Workbook()
    worksheet = workbook.active
    worksheet.title = 'newSheet'
    # 插入数据
    row = ["A", "B", "C"]
    worksheet.append(row)
    ws1 = workbook.create_sheet("Mysheet_End")  # insert at the end (default)
    ws2 = workbook.create_sheet("Mysheet_0", 0)  # insert at first position
    ws3 = workbook.create_sheet("Mysheet_pen", -1)  # insert at the penultimate position
    workbook.save('data/new_data_openpyxl_2.xlsx')
    workbook.close()


if __name__ == "__main__":
    xlsx_path = 'data/data.xlsx'
    learn_openpyxl_deal_excel(xlsx_path)

pandas 处理 Excel 文件教程

python 复制代码
import pandas as pd

def learn_pandas_deal_excel(fileName):
	# https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html#pandas.read_excel
	# https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.html?highlight=excel#pandas.DataFrame.to_excel
    # 1 读取文件的同时必须指定工作表:
    sheet = pd.read_excel(fileName, sheet_name='Sheet1', index_col=False)

    # 2 获取单元格值
    # 第一行为标题行,所以从第二行才开始是其数据的第一行(idex=0)
    # print(sheet.head(2))
    # 1) 指定行的值 loc 根据所定义的index来获取行
    # print(sheet.loc[1])
    # print(sheet.iloc[1])
    # 2) 指定列的值
    print(sheet.iloc[:, 0]) # 列下标从 0 开始
    # 3) 获取单元格的值
    # print(sheet.loc[0][2])

    # 3 保存文件
    df = pd.DataFrame([1, 2, 3])
    df.to_excel("data/new_data_pandas.xlsx")


if __name__ == "__main__":
    xls_path = 'data/data.xls'
    xlsx_path = 'data/data.xlsx'
    learn_pandas_deal_excel(xls_path)
    learn_pandas_deal_excel(xlsx_path)

总结

本博客提到的所有代码均可到我的 GitHub 下载。

相关推荐
测试老哥15 分钟前
接口测试的测试用例应该怎么写?
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
Zenova EdgeOS25 分钟前
Python 工业边缘 redis-py 异步实战
开发语言·redis·python
caoerzhong1 小时前
JeeWMS 开源仓库管理系统权限与域验证解析:Java WMS 如何把数据权限管到仓、货主与人
java·python·开源·vue
一木 之林1 小时前
Miniconda 安装与 Jupyter 使用入门
ide·python·jupyter
抓不住时间的沙1 小时前
Butterfly主题 5.7 导航栏添加相册同时设置相册入口密码
css·python·node.js
风合星语2 小时前
2026 机器人工程实例(五):让 Allegro Hand 在 MuJoCo 中完成接触抓取——抓取状态机、稳定抬升与受控释放
c++·python·机器人·仿真
隐擎fox2 小时前
解构无感人机验证底层机制:行为生物轨迹采样、环境评分模型与自动化对抗实战
自动化测试·python·网络协议·tcp/ip·网络爬虫
haidao0313 小时前
氙灯光源技术特性及其在光催化实验中的标准化应用研究
人工智能·python·能源
用户0332126663673 小时前
使用 Python 设置 Excel 行列自适应 【代码示例】
python·excel
Ticnix3 小时前
RAG 的坑不在检索,在"对齐":pgvector 实战手记
python·agent·全栈