Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting xls to csv in Python 3 using xlrd

I'm using Python 3.3 with xlrd and csv modules to convert an xls file to csv. This is my code:

import xlrd
import csv

def csv_from_excel():

    wb = xlrd.open_workbook('MySpreadsheet.xls')
    sh = wb.sheet_by_name('Sheet1')
    your_csv_file = open('test_output.csv', 'wb')
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

    for rownum in range(sh.nrows):

        wr.writerow(sh.row_values(rownum))

    your_csv_file.close()

With that I am receiving this error: TypeError: 'str' does not support the buffer interface

I tried changing the encoding and replaced the line within the loop with this:

wr.writerow(bytes(sh.row_values(rownum),'UTF-8'))

But I get this error: TypeError: encoding or errors without a string argument

Anyone know what may be going wrong?

like image 568
Spill Avatar asked Mar 27 '14 13:03

Spill


People also ask

Does XLRD support CSV?

While xls is an MS Excel workbook binary file. 2, python modules: csv & pandas & xlrd: Both csv and pandas can be used to read . csv file.

How do I use the XLRD module in Python?

To use python xlrd we need to install xlrd package by using the pip command. Without installing the xlrd package we cannot use the same in our code. It retrieves data from a spreadsheet using the xlrd module. It is also used to read, write or modify data from excel files.


1 Answers

Try this

import xlrd
import csv

def csv_from_excel():
    wb = xlrd.open_workbook('MySpreadsheet.xlsx')
    sh = wb.sheet_by_name('Sheet1')
    your_csv_file = open('output.csv', 'w', encoding='utf8')
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

    for rownum in range(sh.nrows):
        wr.writerow(sh.row_values(rownum))

    your_csv_file.close()
like image 78
Levon Avatar answered Oct 02 '22 21:10

Levon