【发布时间】:2015-08-12 06:50:32
【问题描述】:
我想从数据库中读取数据并将其转换为字典列表以将其放入 XLS 文件以进行报告。
我尝试使用 python 代码进行报告,因为我用最少的编程知识编写代码更容易
我想将字典列表中的字典列表写入 XLS 文件。
我尝试生成 xls 文件但没有正确得到结果
data1 = [{'a':1,'b':2,'c':[{'d':4,'e':5},{'d':8,'e':9}]},{'a':5,'b':3,'c':[{'d':8,'e':7},{'d':1,'e':3}]}]
#Output need to be print like this in excel
A B D E
1 2
4 5
8 9
5 3
8 7
1 3
这是我尝试过的代码
try:
import xlwt
except Exception, e:
raise osv.except_osv(_('User Error'), _('Please Install xlwt Library.!'))
filename = 'Report.xls'
string = 'enquiry'
worksheet = wb.add_sheet(string)
data1 = [{'a':1,'b':2,'c':[{'d':4,'e':5},{'d':8,'e':9}]},{'a':5,'b':3,'c':[{'d':8,'e':7},{'d':1,'e':3}]}]
i=0;j=0;m=0;
if data1:
columns = sorted(list(data1[0].keys()))
worksheet.write_merge(0, 0, 0, 9, 'Report')
worksheet.write(2,0,"A")
worksheet.write(2,1,"B")
worksheet.write(2,2,"D")
worksheet.write(2,3,"E")
for i, row in enumerate(data1,3):
for j, col in enumerate(columns):
if type(row[col]) != list:
worksheet.write(i+m, j, row[col], other_tstyle1)
else:
#if list then loop and group it in new cell
if row[col] != []:
row_columns = sorted(list(row[col][0].keys()))
for k, row1 in enumerate(row[col],1):
for l, col1 in enumerate(row_columns):
worksheet.write(k+m+1, l+3, row1[col1])
#iteration of m for new row
m+=1
#m+=1
我得到了这样的输出
A B D E
1 2
4
5
8
9
5 3
8
7
1
3
【问题讨论】:
-
在您的数据中,“C”是一个包含一些对象的列表。我完全不知道如何以及通过什么规则将对象列表转换为结果中的空列。从我的角度来看,前两行的数据应该是: [{'a':1, 'b':2, 'c':'', 'd':'', 'e':''}, { 'a':'', 'b':'', 'c':'', 'd':4, 'e':5}]
-
@m9_psy 问题已更新
标签: python dictionary xls xlwt