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

Django项目中如何将带样式HTML转换为MS Word docx文档并提供下载

实现步骤

1. 安装所需依赖

首先安装HTML转docx的第三方库,执行命令:
pip install python-docx htmldocx

2. 调整views.py逻辑

你现有代码只完成了HTML渲染和响应头的基础配置,缺少HTML转docx的核心处理逻辑,调整后的代码如下:

from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.utils.encoding import urlquote
from htmldocx import HtmlToDocx
import io
from .models import Info

def order_word(request, info_id):
    info = get_object_or_404(Info, id=info_id)
    # 渲染带动态数据的HTML字符串
    html = render_to_string('businessplan/word.html', {'info': info})
    
    # 初始化HTML转docx工具
    docx_parser = HtmlToDocx()
    doc = docx_parser.parse_html_string(html)
    
    # 将docx文件写入字节流
    buffer = io.BytesIO()
    doc.save(buffer)
    buffer.seek(0)
    
    # 配置响应头,修正文件类型和后缀
    response = HttpResponse(
        buffer.getvalue(),
        content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    )
    # 处理中文文件名乱码问题,修正后缀为docx
    filename = f"{info.businessName}-Business Plan.docx"
    response['Content-Disposition'] = f'attachment; filename*=UTF-8\'\'{urlquote(filename)}'
    return response

3. 其他代码调整说明

  • 路由配置、前端下载入口代码无需修改,可正常使用
  • 你现有的HTML模板可直接复用,注意htmldocx仅支持行内CSS样式,不支持外部样式表,复杂样式建议直接写在标签的style属性中

注意事项

  • 如果你的HTML包含图片,需要确保图片路径是绝对路径,或者提前将图片转成base64格式嵌入HTML,否则docx中无法正常显示图片
  • 不支持过于复杂的CSS布局(如flex、grid),建议用表格实现排版需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:45:02