Write multiple text files to one excel workbook on different sheets?

一世执手 提交于 2019-12-12 04:34:57

问题


I have multiple text files with information such as the following:

Agilent Technologies, Inc.
Date|Previous Close|Open|Day Low|Day High
2017-02-12|$50.47|$50.51|$50.02|$50.59

Each text file is named by its ticker that is located on a new line of the text file master.txt. I want one workbook with the above data on each sheet which should be named by the ticker therefore I used the following code:

import xlwt
textfile = "C:/Python27/SublimeText/Stocks/Master/Excel.txt"

with open("master.txt", 'r') as f:
    tickers = [line.rstrip('\n') for line in f]

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


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

for ticker in tickers:
    try:
        f = open("%s.txt" % ticker, 'r+')
    except:
        pass
    row_list = []
    for row in f:
        row_list.append(row.split('|'))
    column_list = zip(*row_list)
    workbook = xlwt.Workbook()
    worksheet = workbook.add_sheet('%s' % ticker)
    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'))

When running the above code each ticker overwrites the last instead of adding a new sheet. Another issue is that data is only transferred to the first column. For example, the example text file I gave above looks like the following in Excel:

Agilent Technologies, Inc.
Date
2017-02-12

回答1:


workbook = xlwt.Workbook() # moved outside the loop
for ticker in tickers:
    with open("%s.txt" % ticker, 'r') as f: 
        worksheet = workbook.add_sheet('%s' % ticker)
        for row, line in enumerate(f):
            line = line.rstrip()
            for col, value in enumerate(line.split('|')):
                if is_number(value):
                    worksheet.write(row, col, float(value), style=style)
                else:
                    worksheet.write(row, col, value)

workbook.save('all_the_files.xls'))


来源:https://stackoverflow.com/questions/42207319/write-multiple-text-files-to-one-excel-workbook-on-different-sheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!