如何使用 Python 读取 Excel 文件?导入 Pandas 库。使用 pd.read_excel() 函数加载 Excel 文件。查看文件内容:df.head()。访问特定表格:df = pd.read_excel('path/to/excel_file.xlsx', sheet_name='Sheet1')。访问特定单元格:value = df.iloc[row_index, column_index]。迭代行和列:for row in df.iterrows()。保存更改:df.to

如何使用 Python 读取 Excel 文件
导入必要的库
首先,你需要导入 Pandas 库来读取 Excel 文件:
<code class="python">import pandas as pd</code>
加载 Excel 文件
立即学习“Python免费学习笔记(深入)”;
使用 pd.read_excel() 函数加载 Excel 文件:
<code class="python">df = pd.read_excel('path/to/excel_file.xlsx')</code>其中 path/to/excel_file.xlsx 是要加载的 Excel 文件的路径。
查看文件内容
要查看已加载文件的头五行为:
<code class="python">df.head()</code>
访问特定表格和单元格
如果你有多个工作表,可以使用 sheet_name 参数指定要读取的工作表:
<code class="python">df = pd.read_excel('path/to/excel_file.xlsx', sheet_name='Sheet1')</code>要访问特定单元格,可以使用 iloc 或 loc 函数:
<code class="python">value = df.iloc[row_index, column_index]</code>
或
<code class="python">value = df.loc[row_label, column_label]</code>
迭代行和列
你可以使用 Pandas 的迭代器来遍历行和列:
<code class="python">for row in df.iterrows():
# row 是一个元组,包含行索引和行数据
print(row)
for col in df.itercols():
# col 是一个元组,包含列名和列数据
print(col)</code>保存更改
如果对文件进行了更改,可以使用 to_excel() 函数保存更改:
<code class="python">df.to_excel('path/to/output_file.xlsx')</code>以上就是python怎么读取excel文件程序的详细内容,更多请关注php中文网其它相关文章!
全网最新最细最实用WPS零基础入门到精通全套教程!带你真正掌握WPS办公! 内含Excel基础操作、函数设计、数据透视表等
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号