我如何在Python中打开一个Excel文件?

如何打开一个Excel文件的文件来读取Python?

我已经打开文本文件,例如,阅读命令sometextfile.txt 。 我如何做一个Excel文件?

你也可以使用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() 

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

如果您正在使用单张工作表的Excel文件,则可以简单地使用:

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

试试xlrd库 。

[编辑] – 从我的评论中可以看到,类似下面的代码片段可能会诀窍。 我在这里假设你只是search一个单词'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) 

这并不像打开一个纯文本文件那样简单,并且需要某种外部模块,因为没有内置任何东西。 这里有一些选项:

http://www.python-excel.org/

如果可能,您可能需要考虑将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() 

您可以使用只需要xlrd的xlpython包。 在这里find它https://pypi.python.org/pypi/xlpython和它的文档在这里https://github.com/morfat/xlpython

这段代码为Python 3.5.2工作。 它打开并保存和优秀。 我目前正在研究如何将数据保存到文件中,但是这是代码:

 import csv excel = csv.writer(open("file1.csv", "wb")) 
 import pandas as pd import os files = os.listdir('path/to/files/directory/') desiredFile = files[i] filePath = 'path/to/files/directory/%s' Ofile = filePath % desiredFile xls_import = pd.read_csv(Ofile) 

现在你可以使用pandasDataFrames的力量!