Skip to content Skip to sidebar Skip to footer

How To Open Xlsx File With Python 3

I have an xlsx file with 1 sheet. I am trying to open it using python 3 (xlrd lib), but I get an empty file! I use this code: file_errors_location = 'C:\\Users\\atheelm\\Documents\

Solution 1:

You can use Pandas pandas.read_excel just like pandas.read_csv:

import pandas as pd
file_errors_location = 'C:\\Users\\atheelm\\Documents\\python excel mission\\errors1.xlsx'df = pd.read_excel(file_errors_location)
print(df)

Solution 2:

There are two modules for reading xls file : openpyxl and xlrd

This script allow you to transform a excel data to list of dictionnaries using xlrd

import xlrd

workbook = xlrd.open_workbook('C:\\Users\\atheelm\\Documents\\python excel mission\\errors1.xlsx')
workbook = xlrd.open_workbook('C:\\Users\\atheelm\\Documents\\python excel mission\\errors1.xlsx', on_demand = True)
worksheet = workbook.sheet_by_index(0)
first_row = [] # The row where we stock the name of the columnfor col inrange(worksheet.ncols):
    first_row.append( worksheet.cell_value(0,col) )
# tronsform the workbook to a list of dictionnary
data =[]
for row inrange(1, worksheet.nrows):
    elm = {}
    for col inrange(worksheet.ncols):
        elm[first_row[col]]=worksheet.cell_value(row,col)
    data.append(elm)
print data

Solution 3:

Unfortunately, the python engine 'xlrd' that is required to read the Excel docs has explicitly removed support for anything other than xls files.

So here's how you can do it now -

Note: This worked for me with the latest version of Pandas (i.e. 1.1.5). Previously, I was using version 0.24.0 and it didn't work so I had to update to latest version.

Solution 4:

Another way to do it:

importopenpyxlworkbook_errors= openpyxl.Workbook()
workbook_errors = openpyxl.load_workbook(file_errors_location)

Post a Comment for "How To Open Xlsx File With Python 3"