如何在 Python 中打开 Excel 文件? [英] How can I open an Excel file in Python?

查看:95
本文介绍了如何在 Python 中打开 Excel 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何打开 Excel 文件以便在 Python 中读取?

我已经使用读取命令打开了文本文件,例如 sometextfile.txt.如何为 Excel 文件执行此操作?

解决方案


在较新版本的 Pandas 中,您可以将工作表名称作为参数传递.

file_name = # 文件路径 + 文件名sheet = # 工作表名称或工作表编号或工作表编号和名称列表将熊猫导入为 pddf = pd.read_excel(io=file_name, sheet_name=sheet)print(df.head(5)) # 打印数据帧的前 5 行

查看文档以获取有关如何传递 sheet_name 的示例:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html

旧版本:
您也可以使用 pandas....>

当您处理包含多个工作表的 Excel 文件时,您可以使用:

将pandas导入为pdxl = pd.ExcelFile(路径 + 文件名)xl.sheet_names>>>[u'Sheet1', u'Sheet2', u'Sheet3']df = xl.parse("Sheet1")df.head()

df.head() 将打印 Excel 文件的前 5 行

如果您使用单个工作表处理 Excel 文件,您可以简单地使用:

将pandas导入为pddf = pd.read_excel(路径+文件名)打印 df.head()

How do I open a file that is an Excel file for reading in Python?

I've opened text files, for example, sometextfile.txt with the reading command. How do I do that for an Excel file?

解决方案

Edit:
In the newer version of pandas, you can pass the sheet name as a parameter.

file_name =  # path to file + file name
sheet =  # sheet name or sheet number or list of sheet numbers and names

import pandas as pd
df = pd.read_excel(io=file_name, sheet_name=sheet)
print(df.head(5))  # print first 5 rows of the dataframe

Check the docs for examples on how to pass sheet_name:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html

Old version:
you can use pandas package as well....

When you are working with an excel file with multiple sheets, you can use:

import pandas as pd
xl = pd.ExcelFile(path + filename)
xl.sheet_names

>>> [u'Sheet1', u'Sheet2', u'Sheet3']

df = xl.parse("Sheet1")
df.head()

df.head() will print first 5 rows of your Excel file

If you're working with an Excel file with a single sheet, you can simply use:

import pandas as pd
df = pd.read_excel(path + filename)
print df.head()

这篇关于如何在 Python 中打开 Excel 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆