简体   繁体   English

将Excel文件的每一列保存在单独的文本文件中

[英]Save each column of an Excel file in a separate text file

I would like to save each column of an excel file in a separate text file. 我想将Excel文件的每一列保存在单独的文本文件中。

For example.. 例如..

ID, contents
1, aaa is bla bla bla
2, ccc is bla bla bla

I would like to save 1 aaa is bla bla bla in a.txt 我想在a.txt保存1 aaa is bla bla bla
and save 2 ccc is blablabla in b.txt . 并保存2 ccc is blablablab.txt

How can I do this in Python? 如何在Python中执行此操作?

If there is a Python question in here, the answer is likely to use csv module :-) 如果这里有Python问题,则答案可能是使用csv模块 :-)

If it is an Excel question, there is a SaveAs option for "Tab Delimited Text (.txt)" and another for "Comma Separated Values (*.csv)". 如果是Excel问题,则“制表符分隔文本(.txt)”有一个“另存为”选项,“逗号分隔值(* .csv)”有一个“另存为”选项。 Here is a step-by-step tutorial: http://www.howtogeek.com/79991/convert-an-excel-spreadsheet-to-a-tab-delimited-text-file/ 这是一个分步教程: http : //www.howtogeek.com/79991/convert-an-excel-spreadsheet-to-a-tab-delimited-text-file/

If you want to control Excel from Python and are on Windows, you can use the COM interface for the Win32API. 如果要在Windows上从Python控制Excel,则可以将COM接口用于Win32API。 Here's a simple example: http://users.rcn.com/python/download/quoter.pyw 这是一个简单的示例: http : //users.rcn.com/python/download/quoter.pyw

Your question asks how to "save each column of an Excel file" but from your example, it looks like you really want to save each row in a separate file. 您的问题询问如何“保存Excel文件的每一列”,但是从您的示例来看,您似乎真的想将每一行保存在单独的文件中。 Raymond has already suggested using the COM interface. Raymond已经建议使用COM接口。 Here's some code which worked for me: 这是一些对我有用的代码:

import win32com.client

STARTROW = 2
ENDROW = 3

xl = win32com.client.Dispatch("Excel.Application")
xl.DisplayAlerts = False

workbook = xl.Workbooks.Open("C:\FULL\PATH\TO\EXCEL\FILE\HERE.xls")
sheet = workbook.ActiveSheet

letter = 'a'
for row in xrange(STARTROW, ENDROW + 1):
    dest = open(letter + ".txt", 'w')
    dest.write("{0},{1}".format(sheet.Cells(row, 1).Text, sheet.Cells(row, 2).Text))
    dest.close()
    letter = chr(ord(letter)+1)

xl.Quit()

If there are more than 26 rows in your file, then you're going to need a better scheme for the destination file names. 如果文件中有26行以上,那么您将需要一种更好的方案来配置目标文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM