Most 'pythonic' way to write list to .xls file?

强颜欢笑 提交于 2019-12-13 21:04:51

问题


the_list = [['a','b','c'],['b','c','d'],['c','d','e']]
output = []
for k in the_list:
    output.append(str(k)[1:-1].replace(',',"\t").replace("'",'').replace(' ',''))

print output
#['a\tb\tc', 'b\tc\td', 'c\td\te']
#for line in output:
    #out_file.write(line + '\n')

I'm trying to get the list into tab-delmited format so i can write to an .xls file but the only way i could figure out how to do it seemed pretty monotonous . I was wondering if anyone knew a quicker, more efficient, and more 'pythonic' way of writing a list to an .xls


回答1:


You can accomplish the formatting you're looking for with a list comprehension

output = ["\t".join(a) for a in the_list]

See python's documentation on join.




回答2:


Use the built-in csv library. http://docs.python.org/2/library/csv.html

Assuming out_file is already opened, as in the commented out parts of your example:

output_writer = csv.writer(out_file, delimiter="\t")
output_writer.writerows(the_list)

To be a bit pedantic, you're trying to write a tab-delimited file rather than actual Excel. Excel can handle tab-delimited files just fine, but if you need true Excel xlwt is the usual library. Using it you'd have something like this:

wb = xlwt.Workbook()
ws = wb.add_sheet('sheet_name')
for rownum, sublist in enumerate(the_list):
    for colnum, value in enumerate(sublist):
        ws.write(rownum, colnum, value)
wb.save(out_file)



回答3:


If you have to write to XLS, I would use the answers given here:

Python - Write to Excel Spreadsheet




回答4:


While using tab separated variables or csv will often work, expect failure if you need UTF-8. You will not see the characters you expect once you get out of the ASCII range.

I have not tried the real Excel products mentioned in saxman01's references, but they might be more suitable if the target is really Excel. Will they handle other character sets? Just something to think about if you need to go international (or even domestic to non-English speaking audience).

Then you could be asking yourself, what would Google Docs do?



来源:https://stackoverflow.com/questions/19305109/most-pythonic-way-to-write-list-to-xls-file

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