【问题标题】:How to iterate and print the list of dictionaries in xls using python如何使用python迭代和打印xls中的字典列表
【发布时间】: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


【解决方案1】:

我想是因为你有

m += 1 

在你的内部 for 循环中。因此,对于 c 中的每个元素,您都将其放在另一行。 (你最后注释掉的那行是对的。)

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

【讨论】:

  • 是的,外部循环是正确的,但如果我使用注释代码 m+=1 中的那个,它会抛出在工作表中覆盖的错误。这只是应用程序中使用的一段代码示例
  • 嗯,我认为这应该是你的问题——而不是关于打印不正常的问题。但是,您需要添加有关错误的更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-26
  • 2017-08-20
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 2020-07-12
  • 2015-09-28
相关资源
最近更新 更多