问题
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:
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])
来源:https://stackoverflow.com/questions/38463349/selecting-multiple-specific-columns-in-excel-and-exporting-to-csv-using-python