Python實(shí)現(xiàn)在word中指定位置插入圖片或表格
docx庫add_picture()方法不支持對(duì)圖片位置的設(shè)置
1、新建表格
新建一個(gè)1行3列的表格,在中間的一列中插入圖片
from docx import Document
from docx.shared import Pt
from docx.oxml.shared import OxmlElement
from docx.enum.text import WD_ALIGN_PARAGRAPH
def add_center_picture(self, image_path_or_stream, width=None, height=None):
# run = self.doc.add_paragraph().add_run()
tab = self.doc.add_table(rows=1, cols=3) # 添加一個(gè)1行3列的空表
cell = tab.cell(0, 1) # 獲取某單元格對(duì)象(從0開始索引)
ph =cell.paragraphs[0]
run = ph.add_run()
# run.add_break()
run.add_picture(image_path_or_stream, width=width, height=height)
2、在第一段右邊加圖片
from docx import Document
from docx.shared import Pt
from docx.oxml.shared import OxmlElement
from docx.enum.text import WD_ALIGN_PARAGRAPH
def add_log_img(doc, log_path):
# log_path : 圖片本地地址
doc.add_picture(log_path, width=Pt(100), height=Pt(100))
doc.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT
return doc
3、指定位置(占位符替換)插入圖片
原模板文檔(箭頭處是占位符)

插入圖片后

from docx import Document
from docx.shared import Inches
from docx.oxml.ns import qn
from docx.enum.text import WD_ALIGN_PARAGRAPH
def center_insert_img(doc, img):
"""插入圖片"""
for paragraph in doc.paragraphs:
# 根據(jù)文檔中的占位符定位圖片插入的位置
if '<<img1>>' in paragraph.text:
# 把占位符去掉
paragraph.text = paragraph.text.replace('<<img1>>', '')
# 添加一個(gè)文字塊
run = paragraph.add_run('')
# 添加一個(gè)'回車換行效果‘
run.add_break()
# 添加圖片并指定大小
run.add_picture(img, width=Inches(6.2))
def save_img_to_doc(img):
"""把圖片保存到doc文件中的指定位置"""
tpl_doc = 'reports/template.docx'
res_doc = 'reports/res/2022-03-11.docx'
# 打開模板文件
document = Document(tpl_doc)
# 插入圖片居中
center_insert_img(document, img)
# 保存結(jié)果文件
document.save(res_doc)
def main():
"""主函數(shù)"""
img = 'imgs/chart.png'
save_img_to_doc(img)
if __name__ == '__main__':
main()
占位符問題
<<img1>>這個(gè)只是占位符,可以換成其他任何的,只要能唯一識(shí)別到,比如ph_img1。有時(shí)無法替換是因?yàn)槌绦蛑凶x取doc文件時(shí)格式問題沒把占位符識(shí)別成一個(gè),可能識(shí)別成了ph_和img1,這個(gè)時(shí)候你把占位符選中,剪切掉然后再粘貼,粘貼時(shí)選擇只粘貼文字就行了。
4、在table的一個(gè)cell中插入圖片
from docx import Document
from docx.shared import Cm #引入cm單位,便于設(shè)置圖片的寬度
from docx.enum.table import WD_TABLE_ALIGNMENT #用于設(shè)置單元格的內(nèi)容居中對(duì)齊
def insert_img2table():
#創(chuàng)建文檔
document = Document()
# 添加表格
tab1 =document.add_table(rows=1,cols=1) #添加一個(gè)1行1列的空表
cell=tab1.cell(0,0) #獲取某單元格對(duì)象(從0開始索引)
# 在單元格中添加段落
c_p1 =cell.paragraphs[0]
c_p1.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER #設(shè)置單元格內(nèi)容居中對(duì)齊
# 在單元格中添加區(qū)塊
c_run1=c_p1.add_run()
# 在單元格(區(qū)塊)中添加圖片
c_run1.add_picture('cat.png',width=Cm(10))
return document
5、python使用docx向word文檔中表格插入圖片并固定縮放
使用python的docx模塊對(duì)word文檔進(jìn)行編輯時(shí),有時(shí)候需要向表格中插入圖片,但是插入的圖片一般是按照原圖片的大小插入的,即使你的word文檔一開始就設(shè)置好了固定寬高,似乎也是不起作用,這個(gè)時(shí)候就需要在插入后,用python去調(diào)整圖片的寬高。
#向word文檔中的第二個(gè)表格的第3行第3列插入了一個(gè)圖片。
#然后獲取當(dāng)前圖片的高度,將其寬度調(diào)整為固定的10.71cm,再然后通過計(jì)算寬度變化的比例,調(diào)整高度的變化。
# 最后將文檔保存為一個(gè)新的docx文件即可
from docx import Document
from docx import shared
# 本腳本用于測(cè)試word文件的表格寫入
document = Document("test.docx")
#向word文檔中的第二個(gè)表格的第3行第3列插入了一個(gè)圖片。
pic = document.tables[1].cell(2,2).paragraphs[0].add_run().add_picture("Output_1.png")
#獲取原圖片的寬度
source_width = pic.width
#設(shè)置圖片插入后的固定寬度
pic.width = shared.Cm(10.71)
#按圖片寬度的縮放比例配置圖片的高度
pic.height = int(pic.height * (pic.width / source_width))
document.save("1.docx")
6、通過python-docx給word文檔中的指定位置添加表格
1.讀取一個(gè)已有的word文檔。docx格式。
2.在該word文檔中,通過一個(gè)給定的文字。找到該位置。在該位置的下方添加一個(gè)表格。例如在圖中“BUG情況表”的下方插入一個(gè)表格
6.1 需求
1.讀取一個(gè)已有的word文檔。docx格式。
2.在該word文檔中,通過一個(gè)給定的文字。找到該位置。在該位置的下方添加一個(gè)表格。例如在圖中“BUG情況表”的下方插入一個(gè)表格

3.表格內(nèi)容如下。要求添加完該表格后,如果表格內(nèi)容發(fā)生變更。還能再次通過該程序,修改表格里的數(shù)據(jù)。

6.2 設(shè)計(jì)
通過python-docx讀取word文檔。通過document.paragraphs定位指定文字的位置。
通過xlwings讀取excel的內(nèi)容,存成list[list[]]。
通過docx的add_table增加一個(gè)表格,并且更改表頭顏色,合并表格等操作
通過識(shí)別表頭的第一行,判斷是否是已經(jīng)存在這個(gè)表格,來決定是否要?jiǎng)h除原表格
# -*- coding: UTF-8 -*-
import sys
from copy import deepcopy
import xlwings
from docx import Document
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
def copy_table_after(table, paragraph):
tbl, p = table._tbl, paragraph._p
new_tbl = deepcopy(tbl)
p.addnext(new_tbl)
def move_table_after(table, paragraph):
tbl, p = table._tbl, paragraph._p
p.addnext(tbl)
def get_excel_date(filename):
'''
獲得excel里的所有內(nèi)容,返回list
:param filename: excel路徑
:return: list[list[]]
'''
app = xlwings.App(visible=False, add_book=True)
app.display_alerts = False
app.screen_updating = False
wb = app.books.open(filename)
sht = wb.sheets[0]
rng = sht.range('A1')
# 把excel里的數(shù)據(jù)讀取成 年-月-日 時(shí):分:秒的格式
my_date_handler = lambda year, month, day, hour, minute, second, **kwargs: "%04i-%02i-%02i %02i:%02i:%02i" % (
year, month, day, hour, minute, second)
# 取出所有內(nèi)容,這里用ig這個(gè)變量,是為了慶祝I.G獲得LOL S8賽季總冠軍
ig = rng.current_region.options(index=False, numbers=int, empty='N/A', dates=my_date_handler)
result = ig.value
wb.close()
app.quit()
return result
def delete_table_with_title(document,expect_text):
allTables = document.tables
for activeTable in allTables:
if activeTable.cell(0, 0).paragraphs[0].text == expect_text:
print('刪除成功')
activeTable._element.getparent().remove(activeTable._element)
def insert_table_after_text(file_name,excel_name,expect_text):
document = Document(file_name)
# 因?yàn)閐ocx讀出來的都是unicode類型的,所以我們要用unicode類型的進(jìn)行查找
expect_text=expect_text.decode('utf-8')
delete_table_with_title(document,expect_text)
target = None
for paragraph in document.paragraphs:
paragraph_text = paragraph.text
if paragraph_text.endswith(expect_text):
target = paragraph
break
if target is not None:
records = get_excel_date(excel_name)
# 獲得excel數(shù)據(jù)的欄數(shù),初始化一個(gè)空的table
col = len(records[0])
table = document.add_table(rows=1, cols=col)
table.style = 'Table Grid'
# 給table加一個(gè)表頭,并且合并第一欄
shading_elm_1 = parse_xml(r'<w:shd {} w:fill="D9E2F3"/>'.format(nsdecls('w')))
table.rows[0].cells[0]._tc.get_or_add_tcPr().append(shading_elm_1)
table.rows[0].cells[0].text=expect_text
table_row=table.rows[0]
first=table_row.cells[0]
end=table_row.cells[-1]
first.merge(end)
# 合并結(jié)束,開始把excel里的內(nèi)容添加到table里
for tr_list in records:
row_cells = table.add_row().cells
index = 0
for td_list in tr_list:
row_cells[index].text = td_list
index = index + 1
# 把添加的table移動(dòng)到指定的位置
move_table_after(table, target)
# 保存
document.save(file_name)
if __name__ == '__main__':
insert_table_after_text('demo2.docx', 'demo.xlsx',"BUG情況表")
最終效果:

到此這篇關(guān)于Python實(shí)現(xiàn)在word中指定位置插入圖片或表格的文章就介紹到這了,更多相關(guān)Python word插入圖片或表格內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pycharm 實(shí)現(xiàn)顯示project 選項(xiàng)卡的方法
今天小編就為大家分享一篇pycharm 實(shí)現(xiàn)顯示project 選項(xiàng)卡的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01
python中實(shí)現(xiàn)延時(shí)回調(diào)普通函數(shù)示例代碼
這篇文章主要給大家介紹了關(guān)于python中實(shí)現(xiàn)延時(shí)回調(diào)普通函數(shù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-09-09
Python爬蟲數(shù)據(jù)處理模塊的安裝使用教程
這篇文章主要為大家介紹了Python爬蟲數(shù)據(jù)處理模塊的安裝使用教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
利用Python實(shí)現(xiàn)多種風(fēng)格的照片處理
這篇文章主要為大家詳細(xì)介紹了如何利用Python一鍵實(shí)現(xiàn)多種風(fēng)格的照片處理并制作可視化GUI界面,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2022-07-07
Python3實(shí)現(xiàn)的爬蟲爬取數(shù)據(jù)并存入mysql數(shù)據(jù)庫操作示例
這篇文章主要介紹了Python3實(shí)現(xiàn)的爬蟲爬取數(shù)據(jù)并存入mysql數(shù)據(jù)庫操作,涉及Python正則爬取數(shù)據(jù)及針對(duì)mysql數(shù)據(jù)庫的存儲(chǔ)操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-06-06

