Search code examples
pythoncsvxlrd

Write a single column of an xlsx file to csv using python xlrd


I am 99% of the way there...

def xl_to_csv(xl_file):
    wb = xlrd.open_workbook(xl_file)
    sh = wb.sheet_by_index(0)
    output = 'output.csv'
    op = open(output, 'wb')
    wr = csv.writer(op, quoting=csv.QUOTE_ALL)

    for rownum in range(sh.nrows):
        part_number = sh.cell(rownum,1)
        #wr.writerow(sh.row_values(rownum))  #writes entire row
        wr.writerow(part_number)
    op.close()

using wr.writerow(sh.row_values(rownum)) I can write the entire row from the Excel file to a CSV, but there are like 150 columns and I only want one of them. So, I'm grabbing the one column that I want using part_number = sh.cell(rownum,1), but I can't seem to get the syntax correct to just write this variable out to a CSV file.

Here's the traceback:

Traceback (most recent call last):
  File "test.py", line 61, in <module>
    xl_to_csv(latest_file)
  File "test.py", line 32, in xl_to_csv
    wr.writerow(part_number)
_csv.Error: sequence expected

Solution

  • Try this:

    wr.writerow([part_number.value])
    

    The argument must be a list-like object.