3

I'm having trouble figuring out how to import Excel files into my Python script. I'm only a few days into Python so I'm guessing it's something very obvious I'm missing. I'm using Python 3 and the tablib module. From the examples on the tablib site, I've worked out how to save files in xls format

    def saveXLS(self, name, data):        
        # Form the dataset with the accompanying headers
        dataTab =  tablib.Dataset()
        dataTab.headers = data[0][:]

        for i in range(1,len(data)):
            dataTab.append(data[i][:])

        with open(self.saveDir + name + ".xls", 'wb') as f:
            f.write(dataTab.xls)     

(I know that loop is horrible and un-Pythonic, but it's important I get results at the moment as it's for work). At the moment, I open the Excel workbook and save it as a text file (I should point out that all my data is tab-delimited and consists of strings, even for numbers).

I open it like this

    def loadTxt(self,name, fileType, data):
            if( fileType == "txt"):            
                with open(self.currentWorkingDir + "\\" + name + ".txt",'r') as f:
                    reader=csv.reader(f,delimiter='\t')
                    for X in reader:
                        data.append(X)

I tried copying the "dbf" example on the tablib website (http://tablib.readthedocs.org/en/latest/api/) to get

    def loadXLS(self):
            self.data = tablib.Dataset()
            self.data = open('Data.xlsx').read()
            return self.datav

And I get an error (as I expected, as I pulled it from my ass)

UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 637: character maps to .

I really have no clue how to figure this out unfortunately, so any advice would be really appreciated.

5 Answers 5

10

You've probably figured it out by now, but for the next person, you need to read the Excel file as binary:

my_input_stream = open("my_file.xlsx", "rb")
my_dataset = tablib.import_set(my_input_stream)
dataset[1:5]
2
  • am trying this but I get UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8e in position 16: invalid start byte.. thinking python version? Am on python3.5
    – lukik
    Dec 6, 2016 at 16:06
  • 1
    I got a TypeError ("expected string or buffer) when trying the above. Fixed with my_input_stream = open("my_file.xlsx", "rb").read(). Also dataset is indexed from zero, so to see the first five rows of data use dataset[0:4].
    – isedwards
    Aug 17, 2017 at 9:40
6

Currently, tablib 0.12.1.

I use this to import a .xlsx databook that I created with tablib, and output to an excel file.

To get it back into tablib:

import tablib

my_dataset = tablib.Dataset()
my_dataset.xlsx = open('input_file.xlsx', 'rb').read()
print(my_dataset)

and returns something like this:

Email                |Id   |Name                       
---------------------|-----|---------

my_name@tablib.com   |0    |My Name          
my_name1@tablib.com  |1    |My Name1               
my_name2@tablib.com  |2    |My Name2          
my_name3@tablib.com  |3    |My Name3
2

It works like this

import tablib
f = open('my_file.xlsx', 'rb')
data = tablib.import_set(f.read(), format='xlsx')
data[0]
1

While earlier answers may be correct at that time, I'm afraid they are now obsolete due to improvements/changes in tablib library, Here's the code that worked for me and hope this helps the next person:

#Importing tablib library
import tablib
my_dataset = tablib.Dataset()
my_dataset.xlsx = open('my_file.xlsx').read()
print my_dataset
0

I see two problems with your dbf example extension. (Which got me on the path of getting my own example working. Thanks!)

  1. The file should be opened in binary mode.
  2. The data should be assigned into the associated Dataset representation.

def loadXLS(self):
  self.data = tablib.Dataset()
  self.data.xls = open('Data.xls', 'rb').read()
  return self.data

I have been unable to get .xlsx working and suspect it requires a specialized input process. I'll be looking into the django_import_export XLSX dataset creation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.