我正在尝试使用python docx库在MS Word文档中插入大量图像,但这太慢了。我大约有900张图像。
我要做的是创建一个带有标签和图像位置的字典。然后,我创建一个带有标签的表(两列)以放置图像,并使用我定义的功能将标签替换为图像。
import docx
import os
document = docx.Document("./" + template)
def insert_image2(image_path, image_label, document, image_inches = 3):
###
#we insert the image path and the image label on the text. The function replaces the label on the text by the image.
#one example for a label could be image_label = "[image]""
###
from docx import Document
from docx.shared import Inches
for table in document.tables:
for row in table.rows:
for cell in row.cells:
for paragraph in cell.paragraphs:
if image_label in paragraph.text:
paragraph.text = paragraph.text.strip().replace(image_label, "")
run = paragraph.add_run()
run.add_picture(image_path, width=Inches(image_inches))
return
polar_values = os.listdir("./plots/polar")
l_fil = [x for x in polar_values if "foundation" not in x]
polar_keys = [i.split("WT", 1)[1].split(".png")[0].strip() for i in l_fil]
polar_dict = dict(zip(polar_keys,polar_values))
even = polar_keys[1:][::2] #even indexed numbers
odd = polar_keys[::2] #odd indexed numbers
#Adding table
table = document.add_table(rows=1, cols=2)
for ind in range(len(odd)):
row = table.add_row().cells
row[0].add_paragraph(odd[ind])
row[1].add_paragraph(even[ind])
for key, value in polar_dict.items():
insert_image2("./plots/polar/" + value, key, document)
document.save(out_file)
编辑我决定使用命令“ 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
如果有其他与此相关的问题,请发回。如果您想做一些完全不同的事情,请发布一个不同的问题。