当前位置:   article > 正文

【pandas】结合xlsxwriter和groupby实现xls导出合并单元格_py padans excelwriter 导出excel 多级表头 合并单元格

py padans excelwriter 导出excel 多级表头 合并单元格

仅记录

1. 问题描述:
想自动实现xlsx合并同类项

2. 实现代码
 

  1. df = pd.DataFrame(dict_w)
  2. out = io.BytesIO()
  3. wb2007 = xlsxwriter.Workbook(out)
  4. worksheet2007 = wb2007.add_worksheet()
  5. format_top = wb2007.add_format({'border': 1, 'bold': True, 'align': 'center', 'valign': 'vcenter'})
  6. format_other = wb2007.add_format({'border': 1, 'align': 'center', 'valign': 'vcenter'})
  7. self_copy = df
  8. cols = list(self_copy.columns.values)
  9. for i, value in enumerate(cols):
  10. worksheet2007.write(0, i, value, format_top)
  11. worksheet2007.write(1, 0, df.values[0, 0], format_other)
  12. worksheet2007.write(1, 6, df.values[0, 6], format_other)
  13. if len(jiluxiang) > 1:
  14. worksheet2007.merge_range(1, 0, len(jiluxiang), 0, df.values[0, 0],
  15. format_other)
  16. worksheet2007.merge_range(1, 6, len(jiluxiang), 6, df.values[0, 6],
  17. format_other)
  18. worksheet2007.set_column('C:C', 30)
  19. worksheet2007.set_column('D:D', 25)
  20. groups = df.groupby(["模块"])
  21. last_begin = 1
  22. last_begin_module = 1
  23. for group1 in groups:
  24. num_in_group1 = group1[1].values.shape[0]
  25. worksheet2007.write(last_begin_module, 1, group1[0], format_other)
  26. worksheet2007.write(last_begin_module, 5, group1[1]["记分"].sum(), format_other)
  27. if num_in_group1 > 1:
  28. worksheet2007.merge_range(last_begin_module, 1, last_begin_module + num_in_group1 - 1, 1,
  29. group1[0],
  30. format_other)
  31. worksheet2007.merge_range(last_begin_module, 5, last_begin_module + num_in_group1 - 1, 5,
  32. group1[1]["记分"].sum(),
  33. format_other)
  34. last_begin_module += num_in_group1
  35. groups2 = group1[1].groupby(["事项"])
  36. for ctc_group in groups2:
  37. num_in_group = ctc_group[1].values.shape[0]
  38. worksheet2007.write(last_begin, 2, ctc_group[0], format_other)
  39. for i in range(num_in_group):
  40. for j in [3, 4]:
  41. worksheet2007.write(last_begin+i, j, ctc_group[1].values[i, j], format_other)
  42. if num_in_group > 1:
  43. worksheet2007.merge_range(last_begin, 2, last_begin+num_in_group-1, 2,
  44. ctc_group[0],
  45. format_other)
  46. last_begin += num_in_group
  47. wb2007.close()

3. 后记
groupby把每一列聚类得到参数传递给merge_range函数
 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/934519
推荐阅读
相关标签
  

闽ICP备14008679号