Most 'pythonic' way to write list to .xls

2019-09-06 19:00发布

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

4条回答
贪生不怕死
2楼-- · 2019-09-06 19:40

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楼-- · 2019-09-06 19:50

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

Python - Write to Excel Spreadsheet

查看更多
时光不老,我们不散
4楼-- · 2019-09-06 19:55

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.

查看更多
放我归山
5楼-- · 2019-09-06 19:57

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?

查看更多
登录 后发表回答