import pandas as pd
# 读取 Excel 文件
def read_excel(file_path, sheet_name=0):
"""
读取 Excel 文件并返回 DataFrame。
参数:
file_path (str): Excel 文件的路径。
sheet_name (str/int, 可选): 要读取的工作表名称或索引,默认为第一个工作表(索引为 0)。
返回:
DataFrame: 包含 Excel 数据的 DataFrame。
"""
try:
# 使用 pandas 的 read_excel 函数读取 Excel 文件
df = pd.read_excel(file_path, sheet_name=sheet_name)
return df
except Exception as e:
print(f"读取文件时出错: {e}")
return None
# 示例用法
if __name__ == "__main__":
file_path = "example.xlsx" # 替换为你的 Excel 文件路径
df = read_excel(file_path)
if df is not None:
print(df.head()) # 打印前几行数据
pandas 库来处理 Excel 文件。pandas 是一个强大的数据处理库,提供了简单易用的接口来读取和写入 Excel 文件。read_excel:该函数接受两个参数:file_path:Excel 文件的路径。sheet_name:要读取的工作表名称或索引,默认为第一个工作表(索引为 0)。pd.read_excel() 函数读取 Excel 文件,并将内容存储在一个 DataFrame 中。__main__ 块中,调用 read_excel 函数并打印读取到的数据的前几行。如果你需要更多帮助或有其他问题,请随时告诉我!
上一篇:python中字符串类型有哪些
下一篇:python字符转换数字
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站