赞
踩
在现代办公自动化中,Excel 文件广泛应用于数据存储、分析和报告。Python 作为一个强大的编程语言,提供了多个库来处理 Excel 文件,其中最受欢迎的是 openpyxl
和 pandas
。本文将深入介绍如何在 Python 中使用这些库来读写 Excel 文件。
openpyxl
是一个 Python 库,用于读写 Excel 2010 及以上版本的 xlsx/xlsm/xltx/xltm 文件。
pip install openpyxl
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")
from openpyxl import load_workbook
# 加载工作簿
wb = load_workbook("example.xlsx")
ws = wb.active
# 读取数据
for row in ws.iter_rows(values_only=True):
print(row)
pandas
是 Python 数据分析的核心库,提供了简单易用的数据结构和数据分析工具。
pip install pandas openpyxl
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)
# 读取 Excel 文件
df = pd.read_excel("example.xlsx")
# 显示数据
print(df)
以下是一个 Python 示例,演示如何使用 pandas
和 openpyxl
库来读取和写入 Excel 文件。这个示例将包括两个主要部分:使用 pandas
进行简单的 Excel 文件读写操作,以及使用 openpyxl
进行更细粒度的操作。我们将这些功能封装在一个名为 excel_example.py
的 Python 文件中。
在运行此脚本之前,请确保已经安装了 pandas
和 openpyxl
:
pip install pandas openpyxl
import pandas as pd from openpyxl import load_workbook def 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.active for 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 写入 Excel write_excel_with_pandas(file_name, data) # 使用 pandas 读取 Excel print("使用 pandas 读取 Excel:") read_excel_with_pandas(file_name) # 使用 openpyxl 读取 Excel print("\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_pandas
和 read_excel_with_openpyxl
分别用于读取 Excel 文件。main
函数中整合了这些操作的流程。运行这个脚本将会创建一个名为 sample.xlsx
的文件,并在其中写入数据,然后使用两种不同的方法读取并打印出这些数据。
openpyxl
时,可以更加细致地控制 Excel 文件的每个方面,如样式、图表等。pandas
提供了更高级的数据处理能力,适合于复杂的数据分析任务。openpyxl
和 pandas
,以便使用最新的功能和修复。通过本文的介绍,您应该能够理解并开始在 Python 中使用 openpyxl
和 pandas
来处理 Excel 文件。无论是进行简单的数据记录还是复杂的数据分析,这些工具都将是您强大的助手。
希望这篇文章能帮助您理解和掌握 Python 中处理 Excel 文件的方法。如果您有任何疑问或建议,请在评论区留言,让我们共同进步!
作者:climber1121
链接:https://blog.csdn.net/climber1121
来源:CSDN
版权声明:本文为博主原创文章,转载请附上原文出处链接和本声明。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。