0

I want to Create Csv from Excel but only with two specific columns.

csv_file = open(csv_file_path, 'w+')
wr = csv.writer(csv_file, quoting=csv.QUOTE_ALL)

for row_num in xrange(sh.nrows):
  wr.writerow(sh.row_values(row_num))

This Script is Writing all rows of sh sheet into Csv file, i want to write only specific columns into my csv with Header "Id" and "Price" .??

3 Answers 3

1

If you don't know the indeces you can do it this way:

import xlrd

wb = xlrd.open_workbook("myfile.xlsx")
sh = wb.sheet_by_index(0)

headers = ['Price', 'Id']
headers_index = []

for index,column in enumerate(sh.row_values(0)):
    if column in headers:
        if column in headers:
            headers_index.append(index)


for row_num in range(sh.nrows):
    output = [sh.row_values(row_num)[x] for x in headers_index]
    wr.writerow(output)

I assume that the headers are in the first row.

Sign up to request clarification or add additional context in comments.

1 Comment

@EMp1 I added the part of the code in which I create the sh object. It works for me. How do you create it? that should work (Python 3)
1
csv_file = open(csv_file_path, 'w+')
wr = csv.writer(csv_file, quoting=csv.QUOTE_ALL)

for row_num in xrange(sh.nrows):
  row = sh.row_values(row_num)
  wr.writerow([row[3], row[4]])

here 3 and 4 are index for columns Id and Price.

Comments

1

Try that for exporting the 3rd and 4th column as an example

for row_num in xrange(sh.nrows): 
     wr.writerow([sh.cell(row_num, 2).value, sh.cell(row_num, 3).value])

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

Comments

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.