import pandas as pd
# Create a test dataframe
df = pd.DataFrame({'Col1': ['a', 'a', 'a', 'b', 'b', 'c'],
'Col2': [1, 5, 3, 3, 4, 7],
'Col3': [2, 6, 0, 12, 21, 31]})
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Define a format for the first category in the group
bold = workbook.add_format({'bold': True})
# Iterate through the dataframe. If row is the first record of the group apply format and the collapsed '+' symbol,
# for the rest records of the group assign them in the same level and hide them
for row in range(0, df.shape[0]):
if df.iloc[row, 0] != df.iloc[row-1, 0]:
cell_format = bold
outline_option = {'collapsed': True}
else:
cell_format = None
outline_option = {'level': 1, 'hidden': True}
worksheet.set_row(row+1, None, cell_format, outline_option)
writer.save()
一切皆有可能。这里有一种方法可以实现你想要的
文件的保存方式如下:
如果展开这些行,您将得到:
如果输出不是您想要的,您可以调整代码以满足您的需要。但我希望你明白了
相关问题 更多 >
编程相关推荐