简体   繁体   English

Python:-如何从 Excel 创建 Csv(对于特定列)

[英]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.

相关问题 Python:如何快速创建一个 pandas 数据框,其中只有来自大型 excel 表的特定列? - Python: How to quickly create a pandas data frame with only specific columns from a big excel sheet? 如何从csv文件的两个特定列创建元组列表? - How to create a list of tuples from two specific columns of a csv file? 如何将 csv 文件中的特定列导入 python? - How can I import specific columns from csv file to python? python(numpy):如何从CSV文件读取特定的列? - python(numpy): how to read specific columns from CSV file? 如何在python中从csv文件绘制两个特定的列 - How to plot two specific columns from a csv file in python 我有一个包含许多列和许多行的 CSV 文件。 如何从 Python 创建一列一 Excel 表? - I have a CSV file with many columns and many rows. How do I create a one column one Excel sheet from Python? 如何使用python从excel中的特定列中提取不可见的注释 - How to extract invisible comments from specific columns in excel using python Python(xlrd):如何从Excel中获取多个特定列的值? - Python (xlrd): How to get values of multiple specific columns from an Excel? 如何使用 Python 从 CSV 文件在 MySQL 中创建列名? - How to create columns names in MySQL using Python from CSV file? Python 2.7,Excel.csv获取特定列&…? - Python 2.7, Excel.csv getting specific columns &…?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM