【pandas】結合xlsxwriter和groupby實現xls導出合併單元格

僅記錄

1. 問題描述:
想自動實現xlsx合併同類項

2. 實現代碼
 

    
    df = pd.DataFrame(dict_w)
    out = io.BytesIO()
    wb2007 = xlsxwriter.Workbook(out)
    worksheet2007 = wb2007.add_worksheet()
    format_top = wb2007.add_format({'border': 1, 'bold': True, 'align': 'center', 'valign': 'vcenter'})
    format_other = wb2007.add_format({'border': 1, 'align': 'center', 'valign': 'vcenter'})
    self_copy = df
    cols = list(self_copy.columns.values)
    for i, value in enumerate(cols):
        worksheet2007.write(0, i, value, format_top)

    worksheet2007.write(1, 0, df.values[0, 0], format_other)
    worksheet2007.write(1, 6, df.values[0, 6], format_other)
    if len(jiluxiang) > 1:
        worksheet2007.merge_range(1, 0, len(jiluxiang), 0,  df.values[0, 0],
                                  format_other)
        worksheet2007.merge_range(1, 6, len(jiluxiang), 6,  df.values[0, 6],
                                  format_other)
    worksheet2007.set_column('C:C', 30)
    worksheet2007.set_column('D:D', 25)
    groups = df.groupby(["模塊"])
    last_begin = 1
    last_begin_module = 1
    for group1 in groups:
        num_in_group1 = group1[1].values.shape[0]
        worksheet2007.write(last_begin_module, 1, group1[0], format_other)
        worksheet2007.write(last_begin_module, 5, group1[1]["記分"].sum(), format_other)
        if num_in_group1 > 1:
            worksheet2007.merge_range(last_begin_module, 1, last_begin_module + num_in_group1 - 1, 1,
                                      group1[0],
                                      format_other)
            worksheet2007.merge_range(last_begin_module, 5, last_begin_module + num_in_group1 - 1, 5,
                                      group1[1]["記分"].sum(),
                                      format_other)
        last_begin_module += num_in_group1
        groups2 = group1[1].groupby(["事項"])
        for ctc_group in groups2:
            num_in_group = ctc_group[1].values.shape[0]
            worksheet2007.write(last_begin, 2, ctc_group[0], format_other)
            for i in range(num_in_group):
                for j in [3, 4]:
                    worksheet2007.write(last_begin+i, j, ctc_group[1].values[i, j], format_other)
            if num_in_group > 1:
                worksheet2007.merge_range(last_begin, 2, last_begin+num_in_group-1, 2,
                                          ctc_group[0],
                                          format_other)
            last_begin += num_in_group
    wb2007.close()

3. 後記
groupby把每一列聚類得到參數傳遞給merge_range函數
 

發佈了67 篇原創文章 · 獲贊 19 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章