如何使用 Django 将数据发送到 word 文档?

How to send data into word document with Django?

我正在使用 Django 我想将一些数据从我的数据库发送到文档 word,我正在使用 Python-Docx 创建 word 文档我使用 class ExportDocx 它可以生成一个静态 word 文件,但我想放置一些动态数据(例如产品 ID =5,名称 =“..”)基本上将“产品”的所有详细信息放入文档

class ExportDocx(APIView):
  def get(self, request, *args, **kwargs):
    queryset=Products.objects.all()
    # create an empty document object
    document = Document()
    document = self.build_document()

    # save document info
    buffer = io.BytesIO()
    document.save(buffer)  # save your memory stream
    buffer.seek(0)  # rewind the stream

    # put them to streaming content response 
    # within docx content_type
    response = StreamingHttpResponse(
        streaming_content=buffer,  # use the stream's content
        content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    )

    response['Content-Disposition'] = 'attachment;filename=Test.docx'
    response["Content-Encoding"] = 'UTF-8'

    return response

 def build_document(self, *args, **kwargs):
    document = Document()
    sections = document.sections
    for section in sections:
        section.top_margin = Inches(0.95)
        section.bottom_margin = Inches(0.95)
        section.left_margin = Inches(0.79)
        section.right_margin = Inches(0.79) 

    # add a header
    document.add_heading("This is a header")

    # add a paragraph
    document.add_paragraph("This is a normal style paragraph")

    # add a paragraph within an italic text then go on with a break.
    paragraph = document.add_paragraph()
    run = paragraph.add_run()
    run.italic = True
    run.add_text("text will have italic style")
    run.add_break()
    
    return document

这是

的URL.py
    path('<int:pk>/testt/', ExportDocx.as_view() , name='generate-testt'),

如何生成它,我认为我需要制作数据字符串以便它可以与 py-docx 一起使用。

对于 python-docx 文档:http://python-docx.readthedocs.io/

所以我发现我需要传递我正在做的模型但是在另一个版本的代码中忘记添加它......基本上,我只需要添加这些代码行,希望这对任何人都有帮助正在读这个。

def get(self, request,pk, *args, **kwargs):
    # create an empty document object
    document = Document()
    product = Product.objects.get(id=pk)
    document = self.build_document(product)

在文档的构建中,我们只需要简单地使用 f'{queryset.xxxx}'

将其字符串化
def build_document(self,queryset):
    document = Document()
    document.add_heading(f'{queryset.first_name}')

对于产品记录,如:record = {"product_id": 5, "name": "Foobar"), you can add it to the document in your build_document()` 方法如:

document.add_paragraph(
    "Product id: %d, Product name: %s"
    % (record.product_id, record.name)
)

还有其他更现代的字符串内插方法,尽管这种 sprintf 风格在大多数情况下都适用。此资源可能是一个不错的起点。