简体   繁体   中英

Selecting multiple specific columns in excel and exporting to CSV using Python

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.

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])  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM