Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python read_excel

作者:你没有爱过我   发布日期:2025-11-15   浏览:74

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"读取Excel文件时出错: {e}")
        return None

# 示例用法
file_path = 'example.xlsx'
df = read_excel(file_path)
if df is not None:
    print(df.head())  # 打印前5行数据

解释说明:

  1. 导入pandas库import pandas as pd,pandas是一个强大的数据处理库,提供了read_excel函数用于读取Excel文件。
  2. 定义read_excel函数:该函数接受两个参数:
    • file_path:Excel文件的路径。
    • sheet_name:要读取的工作表名称或索引,默认为第一个工作表(索引为0)。
  3. 读取Excel文件:使用pd.read_excel函数读取Excel文件,并将结果存储在DataFrame对象中。
  4. 异常处理:如果读取过程中发生错误,捕获异常并打印错误信息,返回None
  5. 示例用法:提供了一个简单的示例,展示如何调用read_excel函数并打印前5行数据。

上一篇:python中//是什么意思

下一篇:python astype

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站