0

I'm trying to extract 3 columns in a large excel spreadsheet and export it to CSV format. I have XLRD but have found that there are no column specific tools I can use (Or maybe I just overlooked it).

An example excel spreadsheet I have looks like the following

Column1        Column2         Column3        Column4         Column5         Column6
1              2               3              4               5               6
1              2               3              4               5               6
1              2               3              4               5               6
1              2               3              4               5               6
1              2               3              4               5               6
1              2               3              4               5               6
1              2               3              4               5               6
1              2               3              4               5               6        

I'm looking to get just Column2, Column5, and Column6 into a CSV. The other columns are for internal use only. I'm been experimenting with python and it looks roughly like this:

import xlrd
import csv

def excelToCSV():

wb = xlrd.open_workbook('my spreadsheet')
sheet = wb.sheet_by_name('Sheet1')
csvFile = open('output', 'wb')
wr = csv.writer(csvFile, quoting=csv.QUOTE_ALL)

for rownum in xrange(sheet.nrows):
    wr.writerow(sheet.row_values(rownum))
    print (sheet.row_values(rownum,3))

The last part is where things kind of fall apart, What I have now only prints column4 and onwards whereas I want to be able to select certain ones (hard coded in). Any advice would be appreciated.

I have also tried adding in something like (3,4) which then only prints column4. With that logic I tried adding another print line but that only comes out unformatted.

*The print statements aren't going to be part of the code, but they do help me visualize whats going to come out. I hope this isn't bad practice.

1 Answer 1

0

Try that for exporting the 2nd and 3rd column as an example

...    
for rownum in xrange(sheet.nrows):
        wr.writerow([sheet.cell(rownum, 1).value, 
                     sheet.cell(rownum, 2).value])  
Sign up to request clarification or add additional context in comments.

1 Comment

That did exactly what I needed it to do! if it's not to much to ask, could you also explain what line does exactly using "cell"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.