当前位置: 首页 > news >正文

【Python基础】一文搞懂:Python 中 Excel 文件的写入与读取

文章目录

    • 1 引言
    • 2 使用 openpyxl
      • 2.1 安装 openpyxl
      • 2.2 写入 Excel 文件
      • 2.3 读取 Excel 文件
    • 3 使用 pandas
      • 3.1 安装 pandas 和 openpyxl
      • 3.2 写入 Excel 文件
      • 3.3 读取 Excel 文件
    • 4 实例演示
      • 4.1 安装所需库
      • 4.2 封装为excel_example.py脚本文件
    • 5 注意事项
    • 6 总结

1 引言

在现代办公自动化中,Excel 文件广泛应用于数据存储、分析和报告。Python 作为一个强大的编程语言,提供了多个库来处理 Excel 文件,其中最受欢迎的是 openpyxlpandas。本文将深入介绍如何在 Python 中使用这些库来读写 Excel 文件。

2 使用 openpyxl

openpyxl 是一个 Python 库,用于读写 Excel 2010 及以上版本的 xlsx/xlsm/xltx/xltm 文件。

2.1 安装 openpyxl

pip install openpyxl

2.2 写入 Excel 文件

from openpyxl import Workbook# 创建工作簿
wb = Workbook()
ws = wb.active# 添加数据
data = [['Name', 'Age', 'City'],['Alice', 30, 'New York'],['Bob', 25, 'Los Angeles']
]for row in data:ws.append(row)# 保存到文件
wb.save("example.xlsx")

2.3 读取 Excel 文件

from openpyxl import load_workbook# 加载工作簿
wb = load_workbook("example.xlsx")
ws = wb.active# 读取数据
for row in ws.iter_rows(values_only=True):print(row)

3 使用 pandas

pandas 是 Python 数据分析的核心库,提供了简单易用的数据结构和数据分析工具。

3.1 安装 pandas 和 openpyxl

pip install pandas openpyxl

3.2 写入 Excel 文件

import pandas as pd# 数据
df = pd.DataFrame({'Name': ['Alice', 'Bob'],'Age': [30, 25],'City': ['New York', 'Los Angeles']
})# 写入 Excel 文件
df.to_excel("example.xlsx", index=False)

3.3 读取 Excel 文件

# 读取 Excel 文件
df = pd.read_excel("example.xlsx")# 显示数据
print(df)

4 实例演示

以下是一个 Python 示例,演示如何使用 pandasopenpyxl 库来读取和写入 Excel 文件。这个示例将包括两个主要部分:使用 pandas 进行简单的 Excel 文件读写操作,以及使用 openpyxl 进行更细粒度的操作。我们将这些功能封装在一个名为 excel_example.py 的 Python 文件中。

4.1 安装所需库

在运行此脚本之前,请确保已经安装了 pandasopenpyxl

pip install pandas openpyxl

4.2 封装为excel_example.py脚本文件

import pandas as pd
from openpyxl import load_workbookdef write_excel_with_pandas(file_name, data):""" 使用 pandas 写入 Excel """df = pd.DataFrame(data)df.to_excel(file_name, index=False)def read_excel_with_pandas(file_name):""" 使用 pandas 读取 Excel """df = pd.read_excel(file_name)print(df)def read_excel_with_openpyxl(file_name):""" 使用 openpyxl 读取 Excel """workbook = load_workbook(filename=file_name)sheet = workbook.activefor row in sheet.iter_rows(values_only=True):print(row)def main():# 文件名file_name = 'example.xlsx'# 数据data = {'Name': ['Alice', 'Bob'],'Age': [30, 25],'City': ['New York', 'Los Angeles']}# 使用 pandas 写入 Excelwrite_excel_with_pandas(file_name, data)# 使用 pandas 读取 Excelprint("使用 pandas 读取 Excel:")read_excel_with_pandas(file_name)# 使用 openpyxl 读取 Excelprint("\n使用 openpyxl 读取 Excel:")read_excel_with_openpyxl(file_name)if __name__ == '__main__':main()

运行以上代码后控制台输出结果:
使用 pandas 读取 Excel:
Name Age City
0 Alice 30 New York
1 Bob 25 Los Angeles

使用 openpyxl 读取 Excel:
(‘Name’, ‘Age’, ‘City’)
(‘Alice’, 30, ‘New York’)
(‘Bob’, 25, ‘Los Angeles’)
同时生成如下Excel文件:“example.xlsx”在这里插入图片描述

在这个脚本中,我们定义了三个函数:write_excel_with_pandas 用于写入 Excel 文件,read_excel_with_pandasread_excel_with_openpyxl 分别用于读取 Excel 文件。main 函数中整合了这些操作的流程。运行这个脚本将会创建一个名为 sample.xlsx 的文件,并在其中写入数据,然后使用两种不同的方法读取并打印出这些数据。

5 注意事项

  • 当使用 openpyxl 时,可以更加细致地控制 Excel 文件的每个方面,如样式、图表等。
  • pandas 提供了更高级的数据处理能力,适合于复杂的数据分析任务。
  • 确保安装了最新版本的 openpyxlpandas,以便使用最新的功能和修复。

6 总结

通过本文的介绍,您应该能够理解并开始在 Python 中使用 openpyxlpandas 来处理 Excel 文件。无论是进行简单的数据记录还是复杂的数据分析,这些工具都将是您强大的助手。


希望这篇文章能帮助您理解和掌握 Python 中处理 Excel 文件的方法。如果您有任何疑问或建议,请在评论区留言,让我们共同进步!

作者:climber1121
链接:https://blog.csdn.net/climber1121
来源:CSDN
版权声明:本文为博主原创文章,转载请附上原文出处链接和本声明。

http://www.lryc.cn/news/278310.html

相关文章:

  • 二叉树题目:完全二叉树插入器
  • 用MATLAB求最短路径(graphshortestpath)和求最小生成树(minspantree),代码演示
  • 用win系统搭建Minecraft世界服务器,MC开服教程,小白开服教程
  • MacOS安装Miniforge、Tensorflow、Jupyter Lab等(2024年最新)
  • iOS 应用上架指南:资料填写及提交审核
  • 车速预测 | Matlab基于RBF径向基神经网络的车速预测模型(多步预测,尾巴图)
  • MySQL 5.7.35下载安装使用_忘记密码_远程授权
  • openGauss学习笔记-194 openGauss 数据库运维-常见故障定位案例-分析查询语句长时间运行的问题
  • GoLang:gRPC协议的介绍以及详细教程,从Protocol开始
  • LeetCode-2645. 构造有效字符串的最少插入数
  • ssm+vue的城投公司企业人事管理系统设计与实现(有报告)。Javaee项目,ssm vue前后端分离项目。
  • nginx基础面试题以及配置文件解析和命令控制
  • 全自动网页生成系统网站源码重构版
  • 【算法每日一练]-动态规划 (保姆级教程 篇16) #纸带 #围栏木桩 #四柱河内塔
  • Grounding 模型 + SAM 报错
  • linux 网络基础配置
  • leetcode-相同的树
  • Leetcode17-好数对的数目(1512)
  • Ubuntu22.04开机左上角下划线闪烁不开机
  • 提升测试多样性,揭秘Pytest插件pytest-randomly
  • C++学习笔记(三十二):c++ 堆内存与栈内存比较
  • 探索Shadowsocks-Android:保护你的网络隐私
  • 蓝桥杯练习题(二)
  • 将文本文件导入Oracle数据库的简便方法:SQL Developer
  • Mac iTerm2 配置
  • R语言下载安装及VScode配置
  • 【hyperledger-fabric】部署Java应用远程访问智能合约
  • SpringBoot 调用mybatis报错:Invalid bound statement (not found):
  • PHP开发日志 ━━ 不同方法判断某个数组中是否存在指定的键名,测试哪种方法效率高
  • 【pytorch学习】 深度学习 教程 and 实战