简体   繁体   English

自动将转换txt转换为xls

[英]Automate conversion txt to xls

I am looking for the cheapest way of automating the conversion of all the text files (tab-delimited) in a folder structure into .xls format, keeping the shape of columns and rows as it is. 我正在寻找最便宜的方法来自动将文件夹结构中的所有文本文件(制表符分隔)转换为.xls格式,保持列和行的形状不变。

Edit: this did the trick: 编辑:这就是诀窍:

import xlwt
import xlrd
f = open('Text.txt', 'r+')
row_list = []
for row in f:
    row_list.append(row.split())
column_list = zip(*row_list)
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sheet1')
i = 0 
for column in column_list:
    for item in range(len(column)):
        worksheet.write(item, i, column[item])
    workbook.save('Excel.xls')
    i+=1

The easiest way would be to just rename all of the files from *.txt to *.xls. 最简单的方法是将所有文件从* .txt重命名为* .xls。 Excel will automatically partition the data, keeping the original shape. Excel将自动对数据进行分区,保持原始形状。

I'm not going to write your code for you, but here is a head start: 我不会为你编写代码,但这是一个良好的开端:

How about this? 这个怎么样?

import xlwt
textfile = "C:/Users/your_path_here/Desktop/test.txt"

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False        


style = xlwt.XFStyle()
style.num_format_str = '#,###0.00'  

#for textfile in textfiles:
f = open(textfile, 'r+')
row_list = []
for row in f:
    row_list.append(row.split('|'))
column_list = zip(*row_list)
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sheet1')
i = 0
for column in column_list:
    for item in range(len(column)):
        value = column[item].strip()
        if is_number(value):
            worksheet.write(item, i, float(value), style=style)
        else:
            worksheet.write(item, i, value)
    i+=1
workbook.save(textfile.replace('.txt', '.xls'))

Sorry, must have pasted in the wrong thing... 对不起,一定是贴错了...

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

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