如何打开一个Excel文件文件以便在Python中读取?
我打开了文本文件,例如,sometextfile.txt使用阅读命令.我如何为Excel文件执行此操作?
Rak*_*van 83
编辑:
在较新版本的pandas中,您可以将工作表名称作为参数传递.
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
Run Code Online (Sandbox Code Playgroud)
查看文档以获取有关如何传递的示例sheet_name:https:
//pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html
旧版本:
你也可以使用pandas包 ....
当您使用具有多个工作表的Excel文件时,您可以使用:
import pandas as pd
xl = pd.ExcelFile(path + filename)
xl.sheet_names
>>> [u'Sheet1', u'Sheet2', u'Sheet3']
df = xl.parse("Sheet1")
df.head()
Run Code Online (Sandbox Code Playgroud)
df.head() 将打印您的Excel文件的前5行
如果您使用单张工作表处理Excel文件,则只需使用:
import pandas as pd
df = pd.read_excel(path + filename)
print df.head()
Run Code Online (Sandbox Code Playgroud)
Jon*_*age 31
试试xlrd库.
[编辑] - 从我的评论中我可以看到,下面的代码片段之类的东西可能会成功.我在这里假设您只是在一列中搜索"john"这个词,但您可以添加更多内容或将其转换为更通用的功能.
from xlrd import open_workbook
book = open_workbook('simple.xls',on_demand=True)
for name in book.sheet_names():
if name.endswith('2'):
sheet = book.sheet_by_name(name)
# Attempt to find a matching row (search the first column for 'john')
rowIndex = -1
for cell in sheet.col(0): #
if 'john' in cell.value:
break
# If we found the row, print it
if row != -1:
cells = sheet.row(row)
for cell in cells:
print cell.value
book.unload_sheet(name)
Run Code Online (Sandbox Code Playgroud)
Don*_*ner 16
这不像打开纯文本文件那么简单,并且需要某种外部模块,因为没有内置任何内容来执行此操作.以下是一些选项:
如果可能,您可能需要考虑将Excel电子表格导出为CSV文件,然后使用内置的python csv模块来读取它:
http://docs.python.org/library/csv.html
有openpxyl包:
>>> from openpyxl import load_workbook
>>> wb2 = load_workbook('test.xlsx')
>>> print wb2.get_sheet_names()
['Sheet2', 'New Title', 'Sheet1']
>>> worksheet1 = wb2['Sheet1'] # one way to load a worksheet
>>> worksheet2 = wb2.get_sheet_by_name('Sheet2') # another way to load a worksheet
>>> print(worksheet1['D18'].value)
3
>>> for row in worksheet1.iter_rows():
>>> print row[0].value()
Run Code Online (Sandbox Code Playgroud)