将文本文档拆分为Excel工作表xls

时间:2015-10-06 14:13:52

标签: python excel split xlrd xlwt

我目前正在尝试将我拥有的文本文档导出/转换为.xls文件。所以在我发现之后我能够创建一个xls但现在我只需要从文本文档中获取格式正确的xls。

这是我想要做的一个例子。

假设我有以下文本文档: numbers.txt

|<DOg>|
    |Data1 = 300    |
    |Data2 = 200    |
    |Data3 = 15 |
    |Data4 = 14 |
    |Data5 = 4  |
|<DOg>|
    |Data1 = 800    |
    |Data2 = 500    |
    |Data3 = 25 |
    |Data4 = 10 |
    |Data5 = 5  |

如果我使用|作为分隔符运行我的代码,我会将其作为.xls文件

excel

如您所见,格式化已关闭。

我想要获得的目标是以下格式化。

excelFormatted

我正在使用的当前代码如下:

mypath = raw_input("Please enter the directory path for the input files: ")

from os import listdir
from os.path import isfile, join
textfiles = [ join(mypath,f) for f in listdir(mypath) if isfile(join(mypath,f)) and '.txt' in  f]

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

import xlwt
import xlrd

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)
    # for column_list in f:
    #     column_list.append(column.split('|'))
    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'))

我的想法是对列使用.split()方法但是我不确定如何正确实现,因为当我使用split列时,每一行最终都是它自己的柱。

3 个答案:

答案 0 :(得分:3)

如果我正确地阅读了这个问题,我猜你可以将它转换为逗号分隔格式,因此将其用作csv文件。

>>> for i in f.readlines():
...   print i
... 
|Data1 = 300    |

|Data2 = 200    |

|Data3 = 15 |

|Data4 = 14 |

|Data5 = 4  |

|<DOg>|

|Data1 = 800    |

|Data2 = 500    |

|Data3 = 25 |

|Data4 = 10 |

>>> f.seek(0)
for i in f.readlines():
...   if "=" in i:
...     "".join(",".join(i.split("=")).split("|")).strip()
'Data1 , 300'
'Data2 , 200'
'Data3 , 15'
'Data4 , 14'
'Data5 , 4'
'Data1 , 800'

您可以修改脚本以将其写入另一个文件,并可能将其格式化为完美的csv文件。

答案 1 :(得分:2)

看起来你有无限的列。您需要捕获数组中的所有结果并按如下方式转置它们:

import re

# Strip all spaces and dump all data into an array
lines = [mo for mo in re.findall('(?s)(?<=\|)([<\w].+?)\s+?\|', open('py.txt').read())]
# Create an array to hold the transformation
combined = ['' for x in range(len(lines) / lines.count("<DOg>|"))]
# Append by rows
for idx in range(len(lines)):
  combined[idx % len(combined)] += lines[idx] + ','

# Write array to file
output = open('numbersConverted.csv','w')
for comb in combined:
  output.write(comb + "\n")
output.close

这会将您的结果转储到numberConverted.csv中,以便导入。

答案 2 :(得分:1)

def convert_for_excel(data):
    import re
    with open(data, 'r') as f:
        st = ' '.join(f.readlines())
        li = [x for x in re.split(r'\s*\|',st) if x]
        # find <DOg> indices
        ind_of_dog = [i for i, x in enumerate(li) if x == '<DOg>' ]
        # break the list into sublists by indices of <DOg>
        all_lines = [ li[i:j] for i, j in zip([0]+ind_of_dog, ind_of_dog+[None]) if li[i:j]]
        # zip sublists to make tuples
        # join tuples to make Excel ready strings
        excel_ready = [','.join(t) for t in list(zip(*all_lines)) ]

        return excel_ready


pprint.pprint(convert_for_excel('data'))

['<DOg>,<DOg>',
 'Data1 = 300,Data1 = 800',
 'Data2 = 200,Data2 = 500',
 'Data3 = 15,Data3 = 25',
 'Data4 = 14,Data4 = 10',
 'Data5 = 4,Data5 = 5']