如何将字典保存为Excel文件

0 投票
1 回答
2239 浏览
提问于 2025-04-17 23:50

我想把一个字典保存成这样的格式:

Allfiles={'woof': '0', 'jpg': '0', 'js': '45', 'gif': '0', 'css': '11', 'png': '6'} 

然后存成Excel文件。

我的代码是这样的:

workbook=xlwt.Workbook(encoding='ascii')
sheet1=workbook.add_sheet('Parsed data')
for col, caption in enumerate(Allfiles):
    sheet1.write(0,col,caption)
    for row,item in enumerate(Allfiles[caption]):
        sheet1.write(row+1,col,str(item))
workbook.save('savexl.xls')

但是当我查看Excel时,结果非常奇怪。抱歉,我的信誉不够,无法上传图片,但问题是程序把整数'11'和'45'当成字符串处理,放在了不同的单元格里。不过如果我不把这些值设置为字符串,就会出现错误,提示“int is not iterable”(整数不可迭代)。有没有人能帮帮我?


更新:我有一个新的字典,格式是:

Alllists={'scrip': ['10.183.195.140'], 'host': ['edigitalsurvey.com', 'ichef.bbci.co.uk',        'notify3.dropbox.com', 'sa.bbc.co.uk', 'static.bbci.co.uk', 'www.bbc.co.uk'], 'dstip': ['108.160.162.38', '212.58.244.69', '46.236.9.36', '77.72.112.168', '81.23.53.170', '81.23.53.171'], 'referer':    ['http://static.bbci.co.uk/frameworks/barlesque/2.60.6/orb/4/style/orb-fixed.css', 'http://static.bbci.co.uk/h4discoveryzone/0.233.1/style/h4discoveryzone.css', 'http://static.bbci.co.uk/h4drawers/0.66.1/style/h4drawers.css', 'http://static.bbci.co.uk/h4more/0.114.2/style/h4more.css', 'http://static.bbci.co.uk/h4popular/0.130.1/style/h4popular.css', 'http://static.bbci.co.uk/h4whatson/0.176.5/style/h4whatson.css', 'http://www.bbc.co.uk/'], 'server': []}

当我使用以下代码时:

for col,caption in enumerate(Alllists):
    sheet1.write(4,col,caption)
    for row,item in enumerate(Alllists[caption]):
        sheet1.write(row+1,col,item)
workbook.save('savexl.xls')

顺便说一下,这个新的字典应该在Excel文件中保存到前面两个字典的下面。

我得到了一个错误提示:

sheet1.write(row+1,col,item)
Exception: Attempt to overwrite cell: sheetname=u'Parsed data' rowx=1 colx=0

有没有人有什么想法?

1 个回答

1

你的字典只有一行,而不是多行的列表。你可以把字典的结构改成这样:

Allfiles={'woof': [0], 'jpg': [0], 'js': [45], 'gif': [0], 'css': [11], 'png': [6]} 

或者把你的循环改成下面这样:

workbook=xlwt.Workbook(encoding='ascii')
sheet1=workbook.add_sheet('Parsed data')
for col, caption in enumerate(Allfiles):
    sheet1.write(0,col,caption)
    sheet1.write(1,col,Allfiles[caption])
workbook.save('savexl.xls')

这样就可以正常使用原来的字典了。

你代码不报错的唯一原因是因为在Python中,字符串可以被当作字符列表来处理,所以你可以把'11'看作是['1', '1']。

撰写回答