Django使用Openpyxl导出Excel时列宽设置异常问题咨询
问题根因
- 你使用的
save_virtual_workbook是openpyxl早已废弃的接口,保存文件时会丢失部分格式配置,是列宽设置失效的核心诱因 - openpyxl的列宽单位基准与Excel界面显示单位存在差异,且受默认字体匹配度影响,会出现固定比例的偏差
修复方案
第一步:替换废弃的虚拟保存逻辑
将views.py中依赖save_virtual_workbook的代码替换为标准的BytesIO流保存:
from io import BytesIO ... wb = create_workbook() file_text = "some_file_name" # 替换原有保存逻辑 output = BytesIO() wb.save(output) output.seek(0) # 注意修正content_type为xlsx的标准MIME类型 response = HttpResponse( content=output.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) response['Content-Disposition'] = f'attachment; filename={file_text}.xlsx' return response
第二步:列宽单位适配
如果替换保存逻辑后仍存在少量偏差,可以根据你测试得出的比例做换算,你当前环境下的换算公式为:
要得到Excel中x的显示宽度,openpyxl需要设置的width值为
(x + 0.22) / 0.78
你可以在functions.py中直接用该公式预处理你的列宽配置:
for key, value in dict_col_width.items(): # 按转换公式赋值 ws.column_dimensions[key].width = (value + 0.22) / 0.78
可选:统一默认字体避免偏差
如果需要跨设备保持列宽一致性,可以显式设置工作簿默认字体和Excel默认字体匹配,避免不同字体字符宽度不同导致的偏差:
from openpyxl.styles import Font, NamedStyle def create_workbook(): dict_col_width = { 'A': 2.22, 'B': 0.5, 'C': 2.33, 'D': 2.89, } dict_row_height = { 1: 44.4, 2: 9.9, 3: 15.6, 4: 85.2, } wb = Workbook() # 显式设置默认字体,和你本地Excel默认字体保持一致即可 normal_style = NamedStyle(name='Normal') normal_style.font = Font(name='宋体', size=11) wb.add_named_style(normal_style) wb._named_styles['Normal'] = normal_style ws = wb.active ws.title = "Some title" ...
内容的提问来源于stack exchange,提问作者finethen
相关产品推荐
相关产品推荐

