最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python操作word的多種庫的實(shí)戰(zhàn)指南

 更新時(shí)間:2025年10月27日 09:10:42   作者:道之極萬物滅  
這篇文章主要為大家詳細(xì)介紹了Python操作word的多種庫的相關(guān)使用,包括python-docx和docxtpl,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下

一、三方庫

python-docx

官網(wǎng):https://www.osgeo.cn/python-docx/

作用:生成word文檔

pip install python-docx

docxtpl

官網(wǎng):https://docxtpl.readthedocs.io/en/latest/#

git:https://github.com/elapouya/python-docx-template/tree/master/tests

作用:根據(jù)word模板生成一份新的word,git test下有很多例子

pip install docxtpl

二.docxtpl的使用

1.替換文字

from docxtpl import DocxTemplate

# 模板文檔
doc = DocxTemplate("D:\Desktop\測試報(bào)告.docx")
# 待替換對象
context = {
    "報(bào)告名稱": "數(shù)據(jù)查詢機(jī)二期V1.0.0測試報(bào)告",
}
# 執(zhí)行替換
doc.render(context)
# 保存新的文檔
doc.save("test.docx")

2.操作表格

語法與django類似

{% cellbg a.bg %} 更改單元格背景色

from datetime import datetime

from docxtpl import DocxTemplate, RichText

# 模板文檔
doc = DocxTemplate("D:\Desktop\測試報(bào)告.docx")
# 待替換對象
# TODO RichText:可以設(shè)置一些樣式:color(字體顏色)、bold(是否加粗)
context = {
    'alerts': [
        {'name': '張三',
         'comment': '初始創(chuàng)建',
         'date': datetime.now().strftime('%Y-%m-%d'),
         'version': RichText('V1.0', color='FF0000', bold=True),
         'audit': '李四/{}'.format(datetime.now().strftime('%Y-%m-%d')),
         'bg': 'FF0000'
         },
        {'name': '李四',
         'comment': '修改報(bào)告',
         'date': datetime.now().strftime('%Y-%m-%d'),
         'version': RichText('V1.0', color='FF0000'),
         'audit': '李四/{}'.format(datetime.now().strftime('%Y-%m-%d')),
         'bg': 'FF0000'
         },
    ],
}
# 執(zhí)行替換
doc.render(context)
# 保存新的文檔
doc.save("test.docx")

3.插入圖片

from datetime import datetime
from docx.shared import Mm
from docxtpl import DocxTemplate, RichText, InlineImage

# 模板文檔
doc = DocxTemplate("D:\Desktop\測試報(bào)告.docx")
# 要插入的圖片1路徑
image1_path = "img.png"
# 要插入的圖片2路徑
image2_path = "img_1.png"
# 創(chuàng)建2張圖片對象
insert_image1 = InlineImage(doc, image1_path, width=Mm(140), height=Mm(50))
insert_image2 = InlineImage(doc, image2_path, width=Mm(140), height=Mm(50))
# 待替換對象
context = {
    "img1": insert_image1,
    "img2": insert_image2,
}
# 執(zhí)行替換
doc.render(context)
# 保存新的文檔
doc.save("test.docx")

4.完整代碼

from datetime import datetime
from docx.shared import Mm
from docxtpl import DocxTemplate, RichText, InlineImage

# 模板文檔
doc = DocxTemplate("D:\Desktop\測試報(bào)告.docx")
# 要插入的圖片1路徑
image1_path = "img.png"
# 要插入的圖片2路徑
image2_path = "img_1.png"
# 創(chuàng)建2張圖片對象
insert_image1 = InlineImage(doc, image1_path, width=Mm(140), height=Mm(50))
insert_image2 = InlineImage(doc, image2_path, width=Mm(140), height=Mm(50))
# 待替換對象
# TODO RichText:可以設(shè)置一些樣式:color(字體顏色)、bold(是否加粗)
context = {
    "報(bào)告名稱": "數(shù)據(jù)查詢機(jī)二期V1.0.0測試報(bào)告",
    "報(bào)告時(shí)間": datetime.now().strftime('%Y-%m-%d'),
    "img1": insert_image1,
    "img2": insert_image2,
    'alerts': [
        {'name': '張三',
         'comment': '初始創(chuàng)建',
         'date': datetime.now().strftime('%Y-%m-%d'),
         'version': RichText('V1.0', color='FF0000', bold=True),
         'audit': '李四/{}'.format(datetime.now().strftime('%Y-%m-%d')),
         'bg': 'FF0000'
         },
        {'name': '李四',
         'comment': '修改報(bào)告',
         'date': datetime.now().strftime('%Y-%m-%d'),
         'version': RichText('V1.0', color='FF0000'),
         'audit': '李四/{}'.format(datetime.now().strftime('%Y-%m-%d')),
         'bg': 'FF0000'
         },
    ],
}
# 執(zhí)行替換
doc.render(context)
# 保存新的文檔
doc.save("test.docx")

三.python-docx的使用

這個(gè)工具一般用法可以看官方文檔,我這里主要說一下,根據(jù)已有的模板生成新的word文檔

1.模板文件

需求:根據(jù)第三個(gè)表批量生成數(shù)據(jù)

from docx import Document
from docx.oxml.ns import qn
from docx.shared import Pt
from copy import deepcopy

class OperationDocx:

    def __init__(self, template_file):
        self.template_file = template_file
        self.document = Document(self.template_file)
        # 獲取模塊里第三個(gè)表格
        self.table = self.document.tables[2]

    def generate_word(self, word_path):
        # TODO 用例等級、負(fù)責(zé)人、用例描述、前置條件、用例步驟、''、預(yù)期結(jié)果
        case_nums = [
            ['P1', 'lijx5', '標(biāo)簽管理列表', '1.已登錄', '1.點(diǎn)擊標(biāo)簽管理', '',
             '1.成功:正確跳轉(zhuǎn)到標(biāo)簽管理頁面,頁面包括標(biāo)簽名稱、標(biāo)簽顏色、創(chuàng)建時(shí)間、創(chuàng)建人、操作的字段;包括操作按鈕和創(chuàng)建標(biāo)簽按鈕;包括標(biāo)簽名稱搜索框可對標(biāo)簽進(jìn)行搜索'],
            ['P1', 'lijx5', '創(chuàng)建標(biāo)簽', '1.已登錄', '1.點(diǎn)擊標(biāo)簽管理\n2.點(diǎn)擊創(chuàng)建標(biāo)簽\n3.標(biāo)簽名稱輸入“測試1”\n4.標(biāo)簽顏色選擇黑色,點(diǎn)擊確定', '',
             '1.\n2.\n3.\n4.成功:標(biāo)簽管理頁面正確顯示名為“測試1”的標(biāo)簽,標(biāo)簽顏色為黑色'], ['P1', 'lijx5', '創(chuàng)建標(biāo)簽名稱字符串超長', '1.已登錄',
                                                                '1.點(diǎn)擊標(biāo)簽管理\n2.點(diǎn)擊創(chuàng)建標(biāo)簽\n3.標(biāo)簽名稱輸入“12345678901”\n4.標(biāo)簽顏色選擇黑色,點(diǎn)擊確定',
                                                                '', '1.\n2.\n3.\n4.成功:頁面提示由于標(biāo)簽名稱過長,無法創(chuàng)建該標(biāo)簽']
        ]
        docx = Document()
        # 設(shè)置字體與大小
        docx.styles['Normal'].font.name = u'宋體'
        docx.styles['Normal'].font.size = Pt(10.5)
        docx.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')
        for case in case_nums:
            new_table = deepcopy(self.table)
            for i in range(1, 8):
                new_table.cell(i, 4).text = case[i - 1].replace('#', '').replace('*', "")
            paragraph = docx.add_paragraph()
            paragraph._p.addnext(new_table._element)
        docx.save(word_path)

if __name__ == '__main__':
    test = OperationDocx(r'D:\Desktop\報(bào)告模板.docx')
    test.generate_word(r'table123.docx')

結(jié)果

2.繪制表格

設(shè)置單元格屬性

from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL # WD_ALIGN_VERTICAL 會報(bào)錯(cuò),不管
from docx.shared import Cm, RGBColor, Pt

path = 'table123.docx'

doc = Document()

table1 = doc.add_table(rows=10, cols=4, style='Table Grid')

for row in range(10):
    for col in range(4):
        # TODO 向單元格寫入數(shù)據(jù)有以下兩種方式
        # table1.cell(row, col).text = str(list1[row][col])
        run = table1.cell(row, col).paragraphs[0].add_run('123456')
        # TODO 單元格文本顏色,http://tools.jb51.net/static/colorpicker/index.html
        run.font.color.rgb = RGBColor(0, 0, 0)
        # TODO 單元格字體
        run.font.name = '宋體'
        # TODO 單元格字體大小
        run.font.size = Pt(12)
        # TODO 單元格文本加粗
        run.bold = True
        # 向單元格插入圖片
        # table1.cell(col, 4).paragraphs[0].add_run().add_picture('1.jpg', width=Cm(10))
        # TODO 單元格數(shù)據(jù)水平對其方式
        table1.cell(row, col).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
        # TODO 單元格數(shù)據(jù)垂直對其方式   TOP:文本與單元格的上邊框?qū)R。CENTER:文本與單元格的中心對齊。BOTTOM:文本與單元格的下邊框?qū)R
        table1.cell(row, col).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
# TODO 合并單元格
for i in range(3, 9):
    cell_1 = table1.cell(i, 1)
    cell_2 = table1.cell(i, 3)
    cell_1.merge(cell_2)
# TODO 對于合并的單元格設(shè)置寬度
  table1.autofit = False
  table1.allow_autofit = False
  table1.columns[0].width = Inches(1.3)
  # table1.rows[0].cells[0].width = Inches(1.5)
doc.save(path)

設(shè)置表格屬性

from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL  # WD_ALIGN_VERTICAL 會報(bào)錯(cuò),不管
from docx.shared import Cm, RGBColor, Pt
from docx.oxml.ns import qn

path = 'table123.docx'

doc = Document()
# TODO 創(chuàng)建表格
table1 = doc.add_table(rows=10, cols=4, style='Table Grid')
# TODO 設(shè)置表格字體屬性
table1.style.font.size = Pt(12)  # 字體大小
table1.style.font.color.rgb = RGBColor(0, 0, 0)  # 字體顏色
table1.style.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER  # 水平居中
col1 = ['測試用例標(biāo)識', '測試需求項(xiàng)', '測試人員', '用例描述', '前置條件', '操作步驟', '測試輸入', '預(yù)期結(jié)果', '實(shí)際結(jié)果', '是否通過']
col3 = ['測試類型', '測試優(yōu)先級', '模塊', '缺陷ID']
# TODO 向第一列和第三列插入數(shù)據(jù)
for col_data in col1:
    col_index = col1.index(col_data)
    run = table1.cell(col_index, 0).paragraphs[0].add_run(col_data)

# TODO 合并單元格
for i in range(3, 9):
    cell_1 = table1.cell(i, 1)
    cell_2 = table1.cell(i, 3)
    cell_1.merge(cell_2)
doc.save(path)

示例

from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL  # WD_ALIGN_VERTICAL 會報(bào)錯(cuò),不管
from docx.shared import Cm, RGBColor, Pt
from docx.oxml.ns import qn

path = 'table123.docx'

doc = Document()
# TODO 創(chuàng)建表格
table1 = doc.add_table(rows=10, cols=4, style='Table Grid')
# TODO 設(shè)置表格字體屬性
table1.style.font.size = Pt(12)  # 字體大小
table1.style.font.color.rgb = RGBColor(0, 0, 0)  # 字體顏色
col1 = ['測試用例標(biāo)識', '測試需求項(xiàng)', '測試人員', '用例描述', '前置條件', '操作步驟', '測試輸入', '預(yù)期結(jié)果', '實(shí)際結(jié)果', '是否通過']
col3 = ['測試類型', '測試優(yōu)先級', '模塊', '', '', '', '', '', '', '缺陷ID']
# TODO 向第一列插入數(shù)據(jù)
for row_index in [0, 2]:
    for col_data in col1:
        col_index = col1.index(col_data)
        if row_index == 2:
            run = table1.cell(col_index, row_index).paragraphs[0].add_run(col3[col_index])
        else:
            run = table1.cell(col_index, row_index).paragraphs[0].add_run(col_data)
        # TODO 單元格文本加粗
        run.bold = True
        # TODO 單元格數(shù)據(jù)水平對其方式
        table1.cell(col_index, row_index).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER

# TODO 合并單元格
for i in range(3, 9):
    cell_1 = table1.cell(i, 1)
    cell_2 = table1.cell(i, 3)
    cell_1.merge(cell_2)
doc.save(path)

from copy import deepcopy
from docx import Document
from docx.oxml.ns import qn
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL  # WD_ALIGN_VERTICAL 會報(bào)錯(cuò),不管
from docx.shared import Pt, Inches
import pandas as pd
from tqdm import tqdm

class GenerateProgramRecordCase:
    """生成測試方案和測試記錄word用例"""

    def __init__(self):
        self.doc = Document()
        # TODO 設(shè)置字體與大小
        self.doc.styles['Normal'].font.name = u'宋體'
        self.doc.styles['Normal'].font.size = Pt(12.5)
        self.doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')

    @staticmethod
    def read_excel(excel_path, excel_sheet):
        """
        讀取excel用例
        :param excel_path: E:\項(xiàng)目\福州\測試用例\運(yùn)行監(jiān)測系統(tǒng)-測試用例.xlsx
        :param excel_sheet:sheet名稱  預(yù)警預(yù)測
        :return:
        """
        excel_data = pd.read_excel(excel_path, excel_sheet)
        data = excel_data.values
        result = []
        case_id = 1
        for i in data[1:]:
            if str(i[3]) != 'nan' and str(i[5]) != 'nan' and str(i[7]) != 'nan' and str(i[8]) != 'nan':
                temporary_data = ["13-"+str(case_id+136), i[3], i[5], i[7], i[8], "□ 通  過      □ 不通過        □ 未測試", ""]
                result.append(temporary_data)
                case_id += 1
        return result

    def generate_word(self, data):
        """
        將excel一條用例轉(zhuǎn)化為word表格
        :param data: ['1-1-1-1', '預(yù)警預(yù)測-運(yùn)行監(jiān)測指標(biāo)體系', '檢查目錄新增功能', '1.右擊根目錄,點(diǎn)擊新增子目錄\n2.右擊新增的目錄,點(diǎn)擊新增同級目錄']
        :return:
        """
        table = self.doc.add_table(rows=7, cols=2, style='Table Grid')
        title = ['測試編號', '測試項(xiàng)目', '功能說明', '測試過程(步驟)', '現(xiàn)象描述', '實(shí)測結(jié)果', '備注']
        for col in range(2):
            for row in range(7):
                # TODO 向單元格寫入數(shù)據(jù)有以下兩種方式
                if col == 0:
                    table.cell(row, col).paragraphs[0].add_run(title[row])
                    # TODO 單元格數(shù)據(jù)水平對其方式
                    table.cell(row, col).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
                else:
                    table.cell(row, col).paragraphs[0].add_run(data[row])
                    # TODO 單元格數(shù)據(jù)水平對其方式
                    table.cell(row, col).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.LEFT
                # TODO 單元格數(shù)據(jù)垂直對其方式   TOP:文本與單元格的上邊框?qū)R。CENTER:文本與單元格的中心對齊。BOTTOM:文本與單元格的下邊框?qū)R
                table.cell(row, col).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
        # TODO 對于合并的單元格設(shè)置寬度
        table.autofit = False
        table.allow_autofit = False
        table.columns[0].width = Inches(2.0)
        table.columns[1].width = Inches(4.0)
        # TODO 輸入一個(gè)空格
        self.doc.add_paragraph()

    def run(self, excel_path, excel_sheet):
        """
        :param excel_path: E:\項(xiàng)目\福州\測試用例\運(yùn)行監(jiān)測系統(tǒng)-測試用例.xlsx
        :param excel_sheet:sheet名稱  預(yù)警預(yù)測
        :return:
        """
        # TODO 生成測試記錄用例
        for i in tqdm(self.read_excel(excel_path, excel_sheet)):
            self.generate_word(i)
        self.doc.save('測試記錄用例.docx')
        # TODO 生成測試方案用例
        docx = Document()
        docx.styles['Normal'].font.name = u'宋體'
        docx.styles['Normal'].font.size = Pt(12)
        docx.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')
        document = Document('測試記錄用例.docx')
        for table in tqdm(document.tables):
            new_table = deepcopy(table)
            for i in range(3):
                row = new_table.rows[-1]
                row._element.getparent().remove(row._element)
                paragraph = docx.add_paragraph()
                paragraph._p.addnext(new_table._element)
        docx.save('測試方案用例.docx')

if __name__ == '__main__':
    test_program = GenerateProgramRecordCase()
    test_program.run(r"E:\項(xiàng)目\福州\測試用例\應(yīng)急系統(tǒng)-測試用例.xlsx", '應(yīng)急演練')

3.根據(jù)前端代碼識別word表格

from bs4 import BeautifulSoup
from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.shared import RGBColor, Pt

# 你的HTML表格字符串
html_table = """
<p>
</p><table style="width: 100%;table-layout: fixed;"><tbody><tr><td colSpan="1" rowSpan="1" width="auto" style="">第一列</td><td colSpan="1" rowSpan="1" width="auto" style=""><strong>第二列</strong></td><td colSpan="1" rowSpan="1" width="auto" style="">第三列</td><td colSpan="1" rowSpan="1" width="auto" style="">第四列</td></tr><tr><td colSpan="2" rowSpan="1" width="auto" style="">1</td><td colSpan="1" rowSpan="1" width="auto" style="display:none"></td><td colspan="1" rowspan="1" width="auto" style="text-align: center;">2</td><td colSpan="1" rowSpan="1" width="auto" style="">3</td></tr><tr><td colSpan="1" rowSpan="1" width="auto" style="">4</td><td colSpan="1" rowSpan="1" width="auto" style="">5</td><td colSpan="1" rowSpan="3" width="auto" style="">6</td><td colSpan="1" rowSpan="1" width="auto" style="">7</td></tr><tr><td colSpan="1" rowSpan="1" width="auto" style="">8</td><td colSpan="1" rowSpan="1" width="auto" style="">9</td><td colSpan="1" rowSpan="1" width="auto" style="display:none"></td><td colSpan="1" rowSpan="1" width="auto" style="">10</td></tr><tr><td colspan="1" rowspan="2" width="auto" style="text-align: right;">11</td><td colSpan="1" rowSpan="1" width="auto" style="">12</td><td colSpan="1" rowSpan="1" width="auto" style="display:none"></td><td colSpan="1" rowSpan="1" width="auto" style="">13</td></tr><tr><td colSpan="1" rowSpan="1" width="auto" style="display:none"></td><td colSpan="1" rowSpan="1" width="auto" style="">14</td><td colSpan="1" rowSpan="1" width="auto" style=""><strong>15</strong></td><td colSpan="1" rowSpan="1" width="auto" style="">16</td></tr></tbody></table><p>
</p>"""
# 使用BeautifulSoup解析HTML
soup = BeautifulSoup(html_table, 'html.parser')

# 找到表格
table = soup.find('table')

# 初始化數(shù)據(jù)結(jié)構(gòu)
data = []

# 解析表格
for row in table.find_all('tr'):
    row_data = []
    for cell in row.find_all(['th', 'td']):
        print(cell.attrs, cell.contents)
        cell_data = {
            "style": cell.attrs['style'],
            "colspan": int(cell.attrs['colspan']),
            "rowspan": int(cell.attrs['rowspan']),
            "value": cell.text,
            "contents": cell.contents
        }
        row_data.append(cell_data)
    data.append(row_data)

# 輸出結(jié)果
# print(json.dumps(data))
doc = Document()
# TODO 創(chuàng)建表格
table1 = doc.add_table(rows=len(data) + 1, cols=len(data[0]), style='Table Grid')
# TODO 設(shè)置表格字體屬性
table1.style.font.size = Pt(12)  # 字體大小
table1.style.font.color.rgb = RGBColor(0, 0, 0)  # 字體顏色
# table1.style.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER  # 水平居中
for i in data:
    for j in i:
        table1.cell(row_idx=data.index(i), col_idx=i.index(j)).paragraphs[0].add_run(j['value'])

for i in data:
    for j in i:
        if j['rowspan'] == 1 and j['colspan'] > 1:
            cell_1 = table1.cell(data.index(i), i.index(j))
            cell_2 = table1.cell(data.index(i), i.index(j) + j['colspan']-1)
            cell_1.merge(cell_2)
        elif j['colspan'] == 1 and j['rowspan'] > 1:
            cell_1 = table1.cell(data.index(i), i.index(j))
            cell_2 = table1.cell(data.index(i)+j['rowspan']-1, i.index(j))
            cell_1.merge(cell_2)
doc.save("test.docx")

以上就是Python操作word的多種庫的實(shí)戰(zhàn)指南的詳細(xì)內(nèi)容,更多關(guān)于Python操作word的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

辉县市| 乌兰察布市| 乳山市| 天等县| 广宗县| 高邑县| 金山区| 北辰区| 门头沟区| 海宁市| 南投县| 耿马| 嘉善县| 英山县| 大余县| 巨野县| 双牌县| 新郑市| 清远市| 大荔县| 大港区| 伊宁市| 高碑店市| 田阳县| 泽普县| 和硕县| 博白县| 娄烦县| 孝昌县| 稷山县| 依兰县| 云浮市| 浪卡子县| 托克托县| 扶余县| 贺兰县| 上虞市| 云霄县| 新泰市| 改则县| 榆树市|