Pandas输出的样式调整

Database and Ruby, Python, History


最近有一个需求是要把 Pandas 导出成 Excel,并且调整样式。Pandas 有默认的 Styler,但默认只会影响在 Jupyter Notebook 里面的输出样式,不会影响 Excel(个别样式可以生效)。

https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.html

比如加上如下的 css 样式之后,每一行就默认不会换行了。

styler = sample_df.style
styler.applymap(lambda x: 'white-space:nowrap;')

如果需要调整 Excel 的列宽,合并单元格,就需要用到 openpyxl .

https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.dimensions.html

https://openpyxl.readthedocs.io/en/stable/editing_worksheets.html#merge-unmerge-cells

import openpyxl

workbook = openpyxl.load_workbook("sample.xlsx")
sheet = workbook.active
sheet.column_dimensions['B'].width = 45
sheet.column_dimensions['E'].width = 80 # 设置列宽度
sheet.merge_cells(start_row=4, end_row=4+9, start_column=10, end_column=10) # 合并单元格
workbook.save("sample.xlsx")