使用 xlsxwriter 在 dict 中迭代的问题

Problems with iteration in dict with using xlsxwriter

一天好时光。我有一个命令。我需要在format中将其保存在excel中。我导入了 xlsxwriter 并尝试使用 for 保存结果。并得到一个错误。有人可以帮我改进错误吗?我会祝福你的。

TypeError: 'int' object is not iterable

#这是字典

repack_values = {
    'rows':
        {1:
            {'area_id': 1, 'indicator_name_id': 4, 'area_name': 'Российская Федерация', 'indicator_name': 'Стоимость основных фондов в отрасли Обрабатывающие производства, млн. руб.', 2002: 7212776, 2003: 7709820, 2004: 8526843, 2005: 3641287, 2006: 4218012, 2007: 5122970, 2008: 6001501, 2009: 6984796, 2010: 7989040, 2011: 8876602, 2012: 9862265, 2013: 11378966, 2014: 13442626, 2015: 15099981, 2016: 16437831, 2017: 18956787},
         2:
            {'area_id': 2, 'indicator_name_id': 4, 'area_name': 'Центральный федеральный округ', 'indicator_name': 'Стоимость основных фондов в отрасли Обрабатывающие производства, млн. руб.', 2002: 1278063, 2003: 1324242, 2004: 1465904, 2005: 966375, 2006: 1153337, 2007: 1441097, 2008: 1715997, 2009: 2038715, 2010: 2358551, 2011: 2458690, 2012: 2652592, 2013: 3045705, 2014: 3415095, 2015: 3821452, 2016: 4219281, 2017: 4750780}},
                 'years': [2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]
                 }

#dict结束

""" 写入 excel """

import xlsxwriter
excel_doc = 'result.xlsx'
workbook = xlsxwriter.Workbook(excel_doc)
worksheet = workbook.add_worksheet()
col_num = 0
for area_id, row in repack_values['rows'].items():
    worksheet.write(0, col_num, row['area_name'])
    for year in repack_values['years']:
        worksheet.write_column(1, col_num, row.get(year))

考虑到您的屏幕截图所需的输出:

# Write headers
worksheet.write(0, 0, "xyz") # enter your text from image for Column=0,Row=0
worksheet.write_row(0, 1, repack_values['years'])

for area_id, row in repack_values['rows'].items():
    worksheet.write(area_id, col_num, row['area_name'])
    worksheet.write_row(area_id, 1, [row[year] for year in repack_values['years']])
workbook.close()

这将以所需格式创建 excel。