在Excel中选择多个特定列并使用Python导出到CSV [英] Selecting multiple specific columns in excel and exporting to CSV using Python

查看:93
本文介绍了在Excel中选择多个特定列并使用Python导出到CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在大型excel电子表格中提取3列,并将其导出为CSV格式.我有XLRD,但发现我没有可以使用的列专用工具(或者也许我只是忽略了它).

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

我拥有的一个示例excel电子表格如下所示

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        

我希望仅将Column2,Column5和Column6转换为CSV.其他列仅供内部使用.我正在尝试使用python,它看起来大致像这样:

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

最后一部分是事物崩溃的地方,我现在仅打印column4及更高版本,而我希望能够选择某些(硬编码).任何建议将不胜感激.

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.

我还尝试添加(3,4)之类的内容,然后仅打印column4.按照这种逻辑,我尝试添加另一条打印行,但只会以未格式化的形式出现.

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.

* print语句不会成为代码的一部分,但它们确实可以帮助我可视化将要发生的事情.我希望这不是坏习惯.

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

这篇关于在Excel中选择多个特定列并使用Python导出到CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆