我有一个包含2000个项目的字典,如下所示:
d = {'10071353': (0, 0), '06030011': (6, 0), '06030016': (2, 10), ...}
鉴于我想将其写入.xlsx
文件,我使用此代码(取自here):
import xlsxwriter
workbook = xlsxwriter.Workbook('myfile.xlsx')
worksheet = workbook.add_worksheet()
row = 0
col = 0
order=sorted(d.keys())
for key in order:
row += 1
worksheet.write(row, col, key)
for item in d[key]:
worksheet.write(row, col + 1, item)
row += 1
workbook.close()
这将生成一个.xlsx
文件,其中包含以下对齐方式:
A B
06030001 0
10
06030002 10
10
06030003 5
10
然而,这是我追求的对齐方式:
A B C
06030001 0 10
06030002 10 10
06030003 5 10
我应该在脚本中更改哪些内容才能实现此目的?
答案 0 :(得分:4)
我认为这应该有所帮助:
import xlsxwriter
workbook = xlsxwriter.Workbook('myfile.xlsx')
worksheet = workbook.add_worksheet()
row = 0
col = 0
order=sorted(d.keys())
for key in order:
row += 1
worksheet.write(row, col, key)
i =1
for item in d[key]:
worksheet.write(row, col + i, item)
i += 1
workbook.close()
IN:
d={'10071353':(0, 0),'06030011':(6, 0),'06030016':(2, 10)
OUT:
A B C
06030001 6 0
06030002 2 10
06030003 0 0
答案 1 :(得分:3)
最好的方法是使用pandas
执行此任务。这里提供了一些文档(http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html)
import pandas as pd
a = {'1':[1,2,3,4], '2':[5,6,7,8]}
a = pd.DataFrame(a)
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
a.to_excel(writer, sheet_name='Sheet1')
writer.save()
您可能需要安装xlsxwriter
包
答案 2 :(得分:2)