要在使用pandas
的to_excel
方法保存DataFrame时根据内容自适应列宽,你需要在保存后使用openpyxl
库手动调整列宽。以下是一个示例:
python
import pandas as pd
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
# 假设unique_rows是你的DataFrame
unique_rows = ...
# 先使用pandas保存数据到Excel
with pd.ExcelWriter('output.xlsx', engine='openpyxl') as writer:
unique_rows.to_excel(writer, sheet_name='Sheet1', index=False)
# 使用openpyxl加载刚才保存的Excel文件
wb = load_workbook('output.xlsx')
ws = wb.active
# 自适应调整列宽
for column_cells in ws.columns:
length = max(len(str(cell.value)) for cell in column_cells if cell.value is not None)
ws.column_dimensions[column_cells[0].column_letter].width = length + 2 # 可以根据需要调整额外的宽度
# 保存调整后的Excel文件
wb.save('output.xlsx')
print("Excel文件已保存,列宽已根据内容自适应调整。")
这段代码首先用pandas
保存DataFrame到Excel文件,然后通过openpyxl
重新打开文件并遍历每一列,根据每列中最长的字符串长度调整列宽。这里简单地将长度加2作为列宽,你可以根据实际情况调整公式以满足特定的宽度需求。注意,此方法主要适用于文本内容,对于数字或日期等格式,可能需要进一步的处理来准确适应其显示需求。