如何使用python迭代和打印xls中的字典列表

时间:2015-08-12 06:50:32

标签: python dictionary xls xlwt

我想从数据库中读取数据并将其转换为字典列表,并将其放入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

1 个答案:

答案 0 :(得分:0)

我认为这是因为你有

m += 1 

在你的内部for循环中。因此,对于c中的每个元素,您要再将它放下一行。 (你最后注释掉的是正确的。)

顺便说一下,最好使用有意义的变量名而不仅仅是变量的字母(例如row_offset)。