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 下载。

相关推荐
wangchunyu1143 小时前
JAVA CompletableFuture异步编程实战
java·开发语言·python
2501_944521594 小时前
Immer 跨端三方库仓颉适配全流程
python·eclipse·django
信誓旦旦的程序猿5 小时前
【Python量化实战宝典 #26】止损与回撤控制手册:移动止损、最大回撤(Python 可跑)
python·1024程序员节·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
2501_944521595 小时前
Deepmerge 跨端三方库仓颉适配全流程
java·python·eclipse·github
Patrick在香港5 小时前
同一行 strftime,两台机器跑出两种日期
python·datetime·时区·locale·日期处理
2601_967987375 小时前
用Python+OpenCV+YOLO写个游戏脚本:从自动瞄准到自动采集的保姆级教程
python·opencv·yolo·目标检测·游戏自动化
meiying88385 小时前
快递单号批量查询Python脚本:从手动到自动化的完整实现
开发语言·python·自动化
人工智能导论实践课5 小时前
【GUI桌面开发3】PyCharm配置外部工具
ide·python·pycharm
一千柯橘5 小时前
LangChain 的实时输出处理: stream_events 和 Streaming
python·langchain·agent
贾公子5 小时前
图片 AIGC 检测接入实战——URL 与 Base64 的取舍、体积校验与「你送过去的可能不是那张图」
python·aigc