[英]Python:- How to create Csv from Excel(for specific columns)
I want to Create Csv from Excel but only with two specific columns.我想从 Excel 创建 Csv 但只有两个特定的列。
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" .??这个脚本正在将所有行的 sh 表写入 Csv 文件,我只想将特定的列写入我的 csv,标题为“Id”和“Price”。??
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.这里 3 和 4 是列 Id 和 Price 的索引。
Try that for exporting the 3rd and 4th column as an example尝试以导出第 3 和第 4 列为例
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参考: 在excel中选择多个特定列并使用Python导出到CSV
If you don't know the indeces you can do it this way:如果你不知道 indeces 你可以这样做:
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.我假设标题在第一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.