创建动态工作表变量

时间:2015-10-07 06:59:37

标签: python excel xlsx xlsxwriter

我有一个包含以下数据的列表:

month = [ "Jan", "Feb", "Mar", "Apr" ]

每个月的数据都存储在JSON中,如:

[{"Master" : [
        {
           "month" : "Jan",
           "Expense" : "50",
           "Income" : "100",
           "Emp" : "1"
        },
        {
           "month" : "Jan",
           "Expense" : "500",
           "Income" : "1000",
           "Emp" : "2"
        },
        {
           "month" : "Feb",
           "Expense" : "50",
           "Income" : "100",
           "Emp" : "1"
        },
        {
           "month" : "Feb",
           "Expense" : "500",
           "Income" : "1000",
           "Emp" : "2"
        },
        {
           "month" : "Mar",
           "Expense" : "50",
           "Income" : "100",
           "Emp" : "2"
        },
        {
           "month" : "Apr",
           "Expense" : "50",
           "Income" : "100",
           "Emp" : "1"
        }
     ]
}]

根据month的价值,我需要将每个月的所有内容写入单独的表单,其中包含名称" Jan"," Feb&#34 ;," Mar"," Apr"等等使用for loop,如:

for i in range(len(month)):
    worksheet[i] = workbook.add_worksheet(month[i])

列表month中的内容可能会发生变化,因此需要动态变量分配。

这可能吗?

1 个答案:

答案 0 :(得分:2)

以下内容应该可以满足您的需求。您可以配置所需的列和月份:

import xlsxwriter
import itertools

data = [{"Master" : [
        {
           "month" : "Jan",
           "Expense" : "50",
           "Income" : "100",
           "Emp" : "1"
        },
        {
           "month" : "Jan",
           "Expense" : "500",
           "Income" : "1000",
           "Emp" : "2"
        },
        {
           "month" : "Feb",
           "Expense" : "50",
           "Income" : "100",
           "Emp" : "1"
        },
        {
           "month" : "Feb",
           "Expense" : "500",
           "Income" : "1000",
           "Emp" : "2"
        },
        {
           "month" : "Mar",
           "Expense" : "50",
           "Income" : "100",
           "Emp" : "2"
        },
        {
           "month" : "Apr",
           "Expense" : "50",
           "Income" : "100",
           "Emp" : "1"
        }
     ]
}]


workbook = xlsxwriter.Workbook('output.xlsx')

# List of required months
months = [ "Jan", "Feb", "Apr" ]    

# List of required columns and required order
columns = ['month', 'Expense', 'Income', 'Emp'] 

for workbook_month in months:
    for data_month, g in itertools.groupby(data[0]['Master'], key=lambda x: x['month']):
        if workbook_month == data_month:
            worksheet = workbook.add_worksheet(workbook_month)
            worksheet.write_row(0, 0, columns)

            for row, entry in enumerate(g, start=1):
                worksheet.write_row(row, 0, [entry[col] for col in columns])

workbook.close()

在这里给出了以下输出,我错过了Mar数据:

enter image description here