user6640983
user6640983

Reputation:

Python Convert Excel tabs to CSV files

I've edited the post to reflect the changes recommended.

def Excel2CSV(ExcelFile, Sheetname, CSVFile):
    import xlrd
    import csv

    workbook = xlrd.open_workbook('C:\Users\Programming\consolidateddataviewsyellowed.xlsx')
    worksheet = workbook.sheet_by_name (ARC)
    csvfile = open (ARC.csv,'wb')
    wr = csv.writer (csvfile, quoting = csv.QUOTE_ALL)

    for rownum in xrange (worksheet.nrows):
    wr.writerow(
        list(x.encode('utf-8') if type (x) == type (u'') else x
             for x in worksheet.row_values (rownum)))

    csvfile.close()


Excel2CSV("C:\Users\username\Desktop\Programming\consolidateddataviewsyellowed.xlsx","ARC","output.csv")

It displays the following error.

Traceback (most recent call last):
  File "C:/Programming/ExceltoCSV.py", line 18, in <module>

  File "C:/Programming/ExceltoCSV.py", line 2, in Excel2CSV
import xlrd
ImportError: No module named xlrd

Any help would be greatly appreciated.

Upvotes: 2

Views: 2318

Answers (1)

rvictordelta
rvictordelta

Reputation: 668

Response to edited code

No module named xlrd indicates that you have not installed the xlrd library. Bottom line, you need to install the xlrd module. Installing a module is an important skill which beginner python users must learn and it can be a little hairy if you aren't tech savvy. Here's where to get started.

First, check if you have pip (a module used to install other modules for python). If you installed python recently and have up-to-date software, you almost certainly already have pip. If not, see this detailed how-to answer elsewhere on stackoverflow: How do I install pip on Windows?

Second, use pip to install the xlrd module. The internet already has a trove of tutorials on this subject, so I will not outline this here. Just Google: "how to pip install a module on your OS here"

Hope this helps!

Old Answer

your code looks good.. Here's the test case I ran using mostly what your wrote. Note that I changed your function so that it uses the arguments rather than hardcoded values. that may be where your trouble is?

def Excel2CSV(ExcelFile, Sheetname, CSVFile):
    import xlrd
    import csv

    workbook = xlrd.open_workbook (ExcelFile)
    worksheet = workbook.sheet_by_name (Sheetname)
    csvfile = open (CSVFile,'wb')
    wr = csv.writer (csvfile, quoting = csv.QUOTE_ALL)

    for rownum in xrange(worksheet.nrows):
        wr.writerow(
            list(x.encode('utf-8') if type (x) == type (u'') else x
                 for x in worksheet.row_values (rownum)))

    csvfile.close()

Excel2CSV("C:\path\to\XLSXfile.xlsx","Sheet_Name","C:\path\to\CSVfile.csv")

Double check that the arguments you are passing are all correct.

Upvotes: 1

Related Questions