我希望将列宽度设置为该列中的最大字符串长度,实际上,我希望调整该列的宽度。
这是我的代码:
styler = df.style
for column in df:
column_length = df[column].astype(str).str.len().max()
#styler.set_properties(subset=[column], **{'width': '200px'})
styler.set_properties(subset=[column], **{'width': str(column_length)+'px'})
styler.to_excel('C:/Users/test.xlsx', index=False)
导出的excel文件中没有设置列宽,我做错了什么?
发布于 2022-11-07 23:04:08
如果有人有同样的问题,这里是解决办法:
writer = pd.ExcelWriter('C:/Users/test.xlsx')
styler.to_excel(writer, sheet_name='report', index=False)
for column in df:
column_length = max((
df[column].astype(str).str.len().max(), # len of largest item
len(str(df[column].name)) # len of column name/header
)) + 1 # adding a little extra space
col_idx = df.columns.get_loc(column)
writer.sheets['report'].set_column(col_idx, col_idx, column_length)
writer.save()
发布于 2022-11-07 21:45:10
您可以使用pandas.options.display.max_colwidth = ...
并设置最大长度。
若要设置导出的excel列宽度,请参阅此堆栈溢出页here。
https://stackoverflow.com/questions/74353197
复制相似问题