Python 如何在MS Word docx中高效地插入大量文件?

Python 如何在MS Word docx中高效地插入大量文件?,python,python-docx,Python,Python Docx,我试图使用PythonDocx库在MS Word文档中插入大量图像,但速度太慢。我有大约900张图片 我的步骤是创建一个带有标签和图像位置的字典。然后我用标签创建一个表(2列)来定位图像,并用我定义的函数用图像替换标签 导入docx 导入操作系统 文档=docx.document(“./”+模板) def insert_image2(图像路径、图像标签、文档、图像英寸=3): ### #我们在文本上插入图像路径和图像标签。该函数用图像替换文本上的标签。 #标签的一个示例是image_label=

我试图使用PythonDocx库在MS Word文档中插入大量图像,但速度太慢。我有大约900张图片

我的步骤是创建一个带有标签和图像位置的字典。然后我用标签创建一个表(2列)来定位图像,并用我定义的函数用图像替换标签

导入docx
导入操作系统
文档=docx.document(“./”+模板)
def insert_image2(图像路径、图像标签、文档、图像英寸=3):
###
#我们在文本上插入图像路径和图像标签。该函数用图像替换文本上的标签。
#标签的一个示例是image_label=“[image]”
###
从docx导入文档
从docx.shared导入英寸
对于document.tables中的表:
对于table.rows中的行:
对于row.cells中的单元格:
对于单元格中的段落。段落:
如果段落.text中的图像标签:
paragration.text=paragration.text.strip().replace(图像\标签“”)
run=段落。添加_run()
运行。添加图片(图像路径,宽度=英寸(图像英寸))
返回
polar_值=os.listdir(“./plots/polar”)
l_fil=[x表示极坐标值中的x,如果“基础”不在x中]
polar_keys=[i.split(“WT”,1)[1]。split(“.png”)[0]。l_fil中i的strip()
polar_dict=dict(zip(polar_键、polar_值))
偶数=极键[1::[::2]#偶数索引数字
奇数=极键[::2]#奇数索引数字
#添加表
表格=文档。添加表格(行=1,列=2)
对于范围内的ind(len(奇数)):
行=表格。添加行()。单元格
行[0]。添加段落(奇数[ind])
第[1]行。添加段落(偶数[ind])
对于键,polar_dict.items()中的值:
插入图像2(“./plots/polar/”+值、键、文档)
document.save(out\u文件)
编辑
我已决定使用命令“run.add_picture(image_path)”,将图像附加到文档底部。

我认为您设计得太过火了。如果要将一组图像插入Word文档,只需使用VBA即可

或者…选择包含图像的文件夹

Sub InsertImages()
    Dim doc As Word.Document
    Dim fd As FileDialog
    Dim vItem As Variant
    Dim mg1 As Range
    Dim mg2 As Range

    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    Set doc = ActiveDocument

    With fd
        .Filters.Add "Images", "*.gif; *.jpg; *.jpeg", 1
        .FilterIndex = 1

        If .Show = -1 Then
            For Each vItem In .SelectedItems
                Set mg2 = ActiveDocument.Range
                mg2.Collapse wdCollapseEnd
                doc.InlineShapes.AddPicture _
                  FileName:=vItem, _
                  LinkToFile:=False, SaveWithDocument:=True, Range:=mg2
                Set mg1 = ActiveDocument.Range
                mg1.Collapse wdCollapseEnd

                mg1.Text = vbCrLF & vbCrLf
            Next vItem
        End If
    End With

    Set fd = Nothing
End Sub
或者…不要选择文件夹;直接映射到它

Sub GetPictures()
    Dim sPic As String
    Dim sPath As String

    sPath = "c:\myfolder\"
    sPic = Dir(sPath & "*.jpg")

    Do While sPic <> ""
        Selection.InlineShapes.AddPicture _
          FileName:=sPath & sPic, _
          LinkToFile:=False, SaveWithDocument:=True
        sPic = Dir
        Selection.TypeParagraph
        Selection.TypeParagraph
    Loop
End Sub
Sub-GetPictures()
作为字符串的Dim-sPic
像细绳一样暗淡
sPath=“c:\myfolder\”
sPic=Dir(sPath和“*.jpg”)
当sPic“”时执行此操作
Selection.InlineShapes.AddPicture_
文件名:=sPath&sPic_
LinkToFile:=False,SaveWithDocument:=True
sPic=Dir
选择.类型段落
选择.类型段落
环
端接头

如果您有与此相关的其他问题,请发回。如果您想做一些完全不同的事情,请发回不同的问题。

我预计时间将用于重复遍历表和单元格。由于需要考虑合并单元格(即使没有合并单元格),这些计算有点耗时。请尝试重新组织代码,以便只遍历表一次,也许在添加新行时可以正确地执行此操作。