将Excel文件导入Python

12

我有一个有关于将xlsx文件导入Python的基础问题。我查看了许多关于相同主题的回答,但是无论我尝试什么,我仍然无法将我的文件导入到Python中。这是我的代码和我收到的错误:

import pandas as pd

import xlrd

file_location = 'C:\Users\cagdak\Desktop\python_self_learning\Coursera\sample_data.xlsx'
workbook = xlrd.open_workbook(file_location)

错误:

IOError: [Errno 2] No such file or directory: 'C:\\Users\\cagdak\\Desktop\\python_self_learning\\Coursera\\sample_data.xlsx'

你的问题是文件未找到,不是导入问题:请确认文件路径是否正确。 - boardrider
提示:您是否验证了xlsx文件在该位置是否存在? - karthikr
是的,它可以。我在这里复制文件夹路径:C:\Users\cagdak\Desktop\python_self_learning\Coursera,Excel文件的名称是:sample_data。 - Cagdas Kanar
4个回答

21

使用pandas可以直接获取Excel文件的列。这是代码。

import pandas
df = pandas.read_excel('sample.xls')

#print the column names
print df.columns

#get the values for a given column
values = df['column_name'].values

#get a data frame with selected columns
FORMAT = ['Col_1', 'Col_2', 'Col_3']
df_selected = df[FORMAT]

1
谢谢,但是我仍然收到“IOError:[Errno 2]没有这样的文件或目录”错误,尽管我百分之百确定文件位置和文件名是正确的。我花了将近3个小时来做这件事。 - Cagdas Kanar
还需要执行 pip install xlrd - Cyberguille

3
你应该使用原始字符串或转义反斜杠,例如:
file_location = r'C:\Users\cagdak\Desktop\python_self_learning\Coursera\sample_data.xlsx'

或者

file_location = 'C:\\Users\\cagdak\\Desktop\python_self_learning\\Coursera\\sample_data.xlsx'

@CagdasKanar 你是否有该文件的读取权限?如果你运行 python -c "import os; print(os.stat(r'C:\Users\cagdak\Desktop\python_self_learning\Coursera\sample_data.xlsx'))",会发生什么? - andy
我应该在笔记本电脑上还是终端上运行这个程序? - Cagdas Kanar
在终端中输入该命令。如果您仍然收到“文件未找到”的错误提示,我怀疑该文件可能并不在您认为的位置上,或者您没有权限让 Python 读取它。 - andy

1

go ahead and try this:

file_location = 'C:/Users/cagdak/Desktop/python_self_learning/Coursera/sample_data.xlsx'

0
如上所述,Pandas支持使用其read_excel()方法读取Excel电子表格。但是,它依赖于许多外部库,具体取决于正在访问哪个版本的Excel/odf。它默认自动选择一个,但可以使用engine参数指定一个。以下是文档的摘录:
"xlrd" supports old-style Excel files (.xls).
"openpyxl" supports newer Excel file formats.
"odf" supports OpenDocument file formats (.odf, .ods, .odt).
"pyxlsb" supports Binary Excel files.
如果所需的库尚未安装,您将看到一个错误消息,建议您安装所需的库。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接