Come posso aprire un file Excel in Python?


87

Come faccio ad aprire un file che è un file Excel per la lettura in Python?

Ho aperto file di testo, ad esempio, sometextfile.txtcon il comando di lettura. Come posso farlo per un file Excel?


2
Quale versione di Excel? Se puoi limitarti ad aprire i file Excel creati da Ecel 2007 o 2010, dovresti essere in grado di analizzare gran parte o tutto il file come XML.
Adam Crossland

Risposte:


97

Modifica:
nella versione più recente di panda, puoi passare il nome del foglio come parametro.

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

Controlla i documenti per esempi su come passare sheet_name:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html

Vecchia versione:
puoi usare anche il pandaspacchetto ....

Quando lavori con un file Excel con più fogli, puoi utilizzare:

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() stamperà le prime 5 righe del file Excel

Se stai lavorando con un file Excel con un singolo foglio, puoi semplicemente usare:

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

2
questa soluzione ottiene il mio voto positivo. con openpyxl, sto riscontrando il seguente problema "InvalidFileException: openpyxl non supporta il vecchio formato di file .xls, usa xlrd per leggere questo file o convertilo nel formato di file .xlsx più recente". D'altra parte pandas gestisce sia i file .xls che .xlsx ... inoltre, leggere un'intera tabella richiede solo una riga di codice.
nathanielng

3
Sarà necessario installare dipendenze opzionali xlrdper la lettura di file Excel e xlwtper la scrittura di file Excel.
Flimm

32

Prova la libreria xlrd .

[Modifica] - da quello che posso vedere dal tuo commento, qualcosa come lo snippet qui sotto potrebbe fare il trucco. Presumo che tu stia cercando solo una colonna per la parola "john", ma potresti aggiungerne di più o trasformarla in una funzione più generica.

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) 

Penso che questo potrebbe essere quello che voglio che faccia: 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) print sheet.cell_value (0,0) book.unload_sheet (name) large_files.py ma non voglio che usi endwith voglio che trovi e stampi righe che contengono un nome particolare ... come Voglio che stampi la riga dell'enorme foglio Excel che contiene i dati di John e non quelli di Bob. Aiuto?
novak

Ti suggerisco di pubblicare questa domanda come domanda separata e di inserire il codice in un blocco di codice.
Jon Cage

Questa è la seconda domanda di una serie di domande correlate; nella terza domanda viene rivelato che il vero file excel è presumibilmente di 1,5 GB e la memoria del computer è descritta come "non sufficiente" ... vedere stackoverflow.com/questions/3241039/…
John Machin

16

Non è così semplice come aprire un file di testo semplice e richiederà una sorta di modulo esterno poiché non è integrato nulla per farlo. Ecco alcune opzioni:

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

Se possibile, potresti prendere in considerazione l'esportazione del foglio di calcolo Excel come file CSV e quindi utilizzare il modulo csv python integrato per leggerlo:

http://docs.python.org/library/csv.html


Ok, non capisco davvero le cose CSV come faccio a fare in modo che Python apra il mio file Excel come modulo CSV? Ho un programma che fa quello che voglio per i file txt e voglio che faccia la stessa cosa per questo file excel ... qual è il modo migliore per andare? Puoi approfondire questo per favore?
novak

Puoi utilizzare un modulo python di terze parti come xlrd o salvare il tuo file Excel in un file CSV, invece di un normale file Excel. Penso che il punto che ti manca è che un file Excel non ha alcuna somiglianza con un file di testo normale. Apri il documento Excel nel blocco note e vedrai cosa intendo. È necessario salvare il file in un formato di testo normale come CSV (valori separati da virgola), che è più facile da leggere con Python, oppure installare e utilizzare un modulo di terze parti in grado di analizzare un file Excel per te.
Donald Miner

Il problema che ho è che il file è davvero molto grande. Come posso salvare il file in formato CSV se non riesco ad aprirlo completamente?
novak

@novak: Il tuo problema è che il tuo file è di 1,5 GB e la memoria del tuo computer "non è sufficiente" ...
John Machin

6

C'è il pacchetto 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()


1

Questo può aiutare:

Questo crea un nodo che accetta un elenco 2D (elenco di elementi di elenco) e li inserisce nel foglio di calcolo Excel. assicurati che gli IN [] siano presenti o genereranno un'eccezione.

questa è una riscrittura del nodo dinamo Excel di Revit per Excel 2013 poiché il nodo preconfezionato predefinito continuava a rompersi. Ho anche un nodo di lettura simile. La sintassi di Excel in Python è delicata.

thnx @CodingNinja - aggiornato :)

###Export Excel - intended to replace malfunctioning excel node

import clr

clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c')
##AddReferenceGUID("{00020813-0000-0000-C000-000000000046}") ''Excel                            C:\Program Files\Microsoft Office\Office15\EXCEL.EXE 
##Need to Verify interop for version 2015 is 15 and node attachemnt for it.
from Microsoft.Office.Interop import  * ##Excel
################################Initialize FP and Sheet ID
##Same functionality as the excel node
strFileName = IN[0]             ##Filename
sheetName = IN[1]               ##Sheet
RowOffset= IN[2]                ##RowOffset
ColOffset= IN[3]                ##COL OFfset
Data=IN[4]                      ##Data
Overwrite=IN[5]                 ##Check for auto-overwtite
XLVisible = False   #IN[6]      ##XL Visible for operation or not?

RowOffset=0
if IN[2]>0:
    RowOffset=IN[2]             ##RowOffset

ColOffset=0
if IN[3]>0:
    ColOffset=IN[3]             ##COL OFfset

if IN[6]<>False:
    XLVisible = True #IN[6]     ##XL Visible for operation or not?

################################Initialize FP and Sheet ID
xlCellTypeLastCell = 11                 #####define special sells value constant
################################
xls = Excel.ApplicationClass()          ####Connect with application
xls.Visible = XLVisible                 ##VISIBLE YES/NO
xls.DisplayAlerts = False               ### ALerts

import os.path

if os.path.isfile(strFileName):
    wb = xls.Workbooks.Open(strFileName, False)     ####Open the file 
else:
    wb = xls.Workbooks.add#         ####Open the file 
    wb.SaveAs(strFileName)
wb.application.visible = XLVisible      ####Show Excel
try:
    ws = wb.Worksheets(sheetName)       ####Get the sheet in the WB base

except:
    ws = wb.sheets.add()                ####If it doesn't exist- add it. use () for object method
    ws.Name = sheetName



#################################
#lastRow for iterating rows
lastRow=ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row
#lastCol for iterating columns
lastCol=ws.UsedRange.SpecialCells(xlCellTypeLastCell).Column
#######################################################################
out=[]                                  ###MESSAGE GATHERING

c=0
r=0
val=""
if Overwrite == False :                 ####Look ahead for non-empty cells to throw error
    for r, row in enumerate(Data):   ####BASE 0## EACH ROW OF DATA ENUMERATED in the 2D array #range( RowOffset, lastRow + RowOffset):
        for c, col in enumerate (row): ####BASE 0## Each colmn in each row is a cell with data ### in range(ColOffset, lastCol + ColOffset):
            if col.Value2 >"" :
                OUT= "ERROR- Cannot overwrite"
                raise ValueError("ERROR- Cannot overwrite")
##out.append(Data[0]) ##append mesage for error
############################################################################

for r, row in enumerate(Data):   ####BASE 0## EACH ROW OF DATA ENUMERATED in the 2D array #range( RowOffset, lastRow + RowOffset):
    for c, col in enumerate (row): ####BASE 0## Each colmn in each row is a cell with data ### in range(ColOffset, lastCol + ColOffset):
        ws.Cells[r+1+RowOffset,c+1+ColOffset].Value2 = col.__str__()

##run macro disbled for debugging excel macro
##xls.Application.Run("Align_data_and_Highlight_Issues")

@CodingNinja È sufficiente? :)
Apsis0215

Sì, molto meglio

0

Questo codice ha funzionato per me con Python 3.5.2. Si apre, salva ed eccelle. Attualmente sto lavorando su come salvare i dati nel file ma questo è il codice:

import csv
excel = csv.writer(open("file1.csv", "wb"))

 


-1
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)

Ora puoi utilizzare la potenza dei DataFrames dei panda!


1
La domanda riguarda la lettura di un file Excel, non un file di testo separato da virgole. I panda sembrano avere una funzione per quello ( pandas.read_excel).
Bart
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.