Hoe kan ik een Excel-bestand openen in Python?

Hoe open ik een bestand dat een Excel-bestand is om in Python te lezen?

Ik heb tekstbestanden geopend, bijvoorbeeld sometextfile.txtmet het leescommando. Hoe doe ik dat voor een Excel-bestand?


Antwoord 1, autoriteit 100%

Bewerken:
In de nieuwere versie van panda’s kun je de bladnaam als parameter doorgeven.

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

Bekijk de documenten voor voorbeelden van het doorgeven van sheet_name:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html

Oude versie:
je kunt ook het pandas-pakketgebruiken….

Als u werkt met een Excel-bestand met meerdere bladen, kunt u het volgende gebruiken:

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()drukt de eerste 5 rijen van uw Excel-bestand af

Als u werkt met een Excel-bestand met een enkel blad, kunt u eenvoudig het volgende gebruiken:

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

Antwoord 2, autoriteit 31%

Probeer de XLRD-bibliotheek .

[bewerken] – Van wat ik kan zien van uw reactie, zoiets als het snippet hieronder de truc kan doen. Ik neem aan dat je gewoon een kolom zoekt voor het woord ‘John’, maar je kunt meer toevoegen of dit in een meer generieke functie maken.

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) 

Antwoord 3, Autoriteit 16%

Dit is niet zo eenvoudig als het openen van een platte tekstbestand en vereist een soort externe module omdat er niets is ingebouwd om dit te doen. Hier zijn enkele opties:

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

Indien mogelijk wilt u rekening houden met het exporteren van het Excel-spreadsheet als een CSV-bestand en vervolgens de ingebouwde Python CSV-module gebruiken om het te lezen:

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


Antwoord 4, Autoriteit 6%

Er is de openpxyl pakket:

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

Antwoord 5

U kunt Xlpython-pakket gebruiken dat alleen XLRD vereist.
Vind het hier https://pypi.python.org/pypi/xlpython
en de documentatie hier https://github.com/morfat/xlpython


Antwoord 6

Dit kan helpen:

Hiermee wordt een knooppunt gemaakt met een 2D-lijst (lijst met lijstitems) en duwt ze in de Excel-spreadsheet. Zorg ervoor dat de in [] S aanwezig zijn of gooien en uitzondering.

Dit is een herschrijf van de Revit Excel Dynamo-knooppunt voor Excel 2013 als het standaard voorverpakte knooppunt bleef breken. Ik heb ook een soortgelijk leesknooppunt. De Excel-syntaxis in Python is aangenaam.

thnx @codeingninja – bijgewerkt 🙂

###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")

Antwoord 7

Deze code werkte voor mij met Python 3.5.2. Het opent en slaat op en blinkt uit. Ik ben momenteel bezig met het opslaan van gegevens in het bestand, maar dit is de code:

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

 


Antwoord 8

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)

Nu kun je de kracht van panda’s DataFrames gebruiken!

Other episodes