【问题标题】:How to insert an Image in a specific position in a word document with python?如何使用python在word文档的特定位置插入图像?
【发布时间】:2021-11-25 00:03:14
【问题描述】:

我的程序创建了一堆单词文件:它们包含有关学生的信息,例如姓名地址电话号码......和条形码。 当我将我的 QRCode 作为图片插入时,它会附加在文件的末尾。我希望将其插入文本 "Barcode" 的最右侧。 我徒劳地寻找解决方案。 我插入了解释这个词的图片。对不起,我隐藏了这些信息,因为它是机密的。 这是我的代码:

import uuid 
import pandas as pd
import pyqrcode 
from docx import Document
from docx.shared import Inches


def generateBarCode(length):
    return str(uuid.uuid4()).replace('-','')[0:length]


df=pd.DataFrame(pd.read_excel('Komplette- 
GastAccountFHZugangsdatenFertig.xlsx'))
array=[]
for i in range(len(df)):
    qr=pyqrcode.create(generateBarCode(8))
    array.append(qr)


df.insert(8,'Barcode',array)
x=['.png']

with pd.ExcelWriter('Komplette-GastAccountFHZugangsdatenFertig.xlsx') as 
writer :
   df.to_excel(writer,sheet_name='Sheet1')

for i in range(len(df)):
    document=Document()
    document.add_heading('Informationen')
    document.add_paragraph('Name : ' + df['Name'][i])
    document.add_paragraph('Vorname : ' + df['Vorname '][i])
    document.add_paragraph('Geschlecht : ' + df['Geschlecht'][i])
    document.add_paragraph('Adresse(in Marokko) : ' + df['Adresse (in 
Marokko)'][i])
    document.add_paragraph('Telefonnummer : ' + str(df['Telefonnummer'][i]))
    document.add_paragraph('E-Mailadresse : ' + str(df['E-Mailadresse'][i]))
    document.add_paragraph('Studiengang : ' + df['Studiengang'][i] )
    document.add_paragraph('Semester : ' + str(df['Semester'][i]))
    document.add_paragraph('Barcode : ')
    qr=df['Barcode'][i]

    qr.png(df['Name'][i]+df['Vorname '][i]+x[0])
    document.add_picture(df['Name'][i]+df['Vorname '] 
[i]+'.png',width=Inches(2.0))

    document.save(df['Name'][i]+' '+ df['Vorname '][i]+'.docx')

截图

谢谢

【问题讨论】:

    标签: python ms-word docx


    【解决方案1】:

    在 python-docx 的文档中查看Document.add_picture 的实现here 给出了

    def add_picture(self, image_path_or_stream, width=None, height=None):
        run = self.add_paragraph().add_run()
        return run.add_picture(image_path_or_stream, width, height)
    

    使用此信息,您可以使用

    document.add_paragraph('Barcode : ')
            .add_run()
            .add_picture(df['Name'][i]+df['Vorname '] [i]+'.png',width=Inches(2.0))
    

    将图片添加到同一段落中。我还没有测试过,但我希望这能解决问题。

    【讨论】:

    • 谢谢,这就是我要找的!
    【解决方案2】:

    用python在word文档的特定位置插入图片

    使用 Python 的 docx 模块,我们可以在文档中的特定位置添加图像

    请参阅我在此处链接的帖子以获取相同的https://stackoverflow.com/a/70099088/17385292

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      相关资源
      最近更新 更多