You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用DataFrame列格式化Excel导出代码时遇Module Not Found错误求助

分析Excel格式化代码的"Module Not Found"错误原因

问题代码

def excel_data(request, data):
    # Create an Excel writer object with custom formatting
    excel_writer = pd.ExcelWriter(BytesIO(), engine='xlsxwriter')
    data.to_excel(excel_writer, sheet_name='Sheet1', index=False)

    # Get the xlsxwriter workbook and worksheet objects
    workbook = excel_writer.book
    worksheet = excel_writer.sheets['Sheet1']

    # Add custom formatting (for example, formatting the 'Percentage' column as a percentage)
    percentage_format = workbook.add_format({'num_format': '0.00%'})
    worksheet.set_column('AZ:AZ', None, percentage_format)

    # Save the Excel file to a BytesIO object
    excel_writer.save()
    excel_data = excel_writer.buffer.getvalue()
    excel_writer.close()

    # Create the HttpResponse with the Excel file
    response = HttpResponse(excel_data, content_type='application/vnd.ms-excel')
    file = "YieldImprovement_Datenexport_" + dt.date.today().strftime("%d%m%Y") + ".xlsx"
    response['Content-Disposition'] = 'attachment; filename="%s"' % file

    return response 

错误原因及解决办法

  • 缺失xlsxwriter库:代码指定了engine='xlsxwriter',这是pandas依赖的第三方Excel写入引擎,未安装时会触发模块找不到错误。执行以下命令安装:
    pip install xlsxwriter
    
  • 缺失pandas库:代码中使用了pd.ExcelWriter和DataFrame的to_excel方法,未安装pandas会导致模块缺失。安装命令:
    pip install pandas
    
  • 缺失Django模块:代码中用到了HttpResponse,这是Django框架的核心模块,如果项目未安装Django或未导入该模块,也会报错。安装Django:
    pip install django
    
    并在代码开头添加导入:
    from django.http import HttpResponse
    
  • 缺失标准库导入:代码中使用的BytesIO(来自io模块)、dt.date(来自datetime模块)需要在代码开头添加导入,否则会引发后续执行错误:
    from io import BytesIO
    import datetime as dt
    import pandas as pd
    

内容的提问来源于stack exchange,提问作者Prasad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 10:42:22