python给word插入脚注

1.需求

最近因为工作需要,需要给大量文本的脚注插入内容,我就写了个小程序。

2.实现

下面程序是我已经给所有脚注插入了两次文本"幸福",给脚注2到4再插入文本"幸福"

复制代码
from win32com import client


def add_text_to_specific_footnotes(filename, start_index, end_index, text_to_add):
    word = client.Dispatch('Word.Application')
    doc = word.Documents.Open(filename)

    try:
        # 遍历指定范围内的脚注索引
        for footnote_index in range(start_index, end_index + 1):
            try:
                # 获取当前索引的脚注
                target_footnote = doc.Footnotes.Item(footnote_index)
                # 直接使用脚注的Range
                r = target_footnote.Range
                # 在脚注中添加文字
                r.InsertAfter(text_to_add)
            except Exception as e:
                print(f"Error adding text to footnote {footnote_index}: {e}")

        # 保存文档
        doc.Save()

    except Exception as e:
        print(f"Error: {e}")

    finally:
        # 关闭文档和 Word 应用程序
        doc.Close()
        word.Quit()


# 示例:在第2到第4个脚注上添加文本
add_text_to_specific_footnotes(r'C:/Users/zhang/Desktop/521.docx', 2, 4, "幸福")

输出的文本插入脚注结果:

文本

脚注

3.这是读取文本内容,然后再插入到脚注的程序

复制代码
from win32com import client
from docx import Document

def read_word_document(file_path):
    doc = Document(file_path)
    paragraphs_list = []

    for paragraph in doc.paragraphs:
        paragraphs_list.append(paragraph.text)

    return paragraphs_list


def add_text_to_specific_footnotes(filename, start_index, end_index, texts_to_add):
    word = client.Dispatch('Word.Application')
    doc = word.Documents.Open(filename)

    try:
        # Check if the length of texts_to_add is equal to the number of footnotes
        if len(texts_to_add) != (end_index - start_index + 1):
            print("Error: Number of texts does not match the number of footnotes.")
            return

        # 遍历指定范围内的脚注索引
        for i, footnote_index in enumerate(range(start_index, end_index + 1)):
            try:
                # 获取当前索引的脚注
                target_footnote = doc.Footnotes.Item(footnote_index)
                # 直接使用脚注的Range
                r = target_footnote.Range
                # 在脚注中添加文字
                r.InsertAfter(texts_to_add[i])
            except Exception as e:
                print(f"Error adding text to footnote {footnote_index}: {e}")

        # 保存文档
        doc.Save()

    except Exception as e:
        print(f"Error: {e}")

    finally:
        # 关闭文档和 Word 应用程序
        doc.Close()
        word.Quit()

# 示例:在第2到第4个脚注上添加文本
# 替换 'your_word_document.docx' 为你的Word文档的文件路径
file_path0 = 'C:/Users/zhang/Desktop/test_python_插入脚注/脚注内容.docx'
paragraphs = read_word_document(file_path0)

length = len(paragraphs)
print(length)
texts_to_add = [paragraphs[0],paragraphs[1],paragraphs[2]]
add_text_to_specific_footnotes(r'C:/Users/zhang/Desktop/test_python_插入脚注/521.docx', 1, length,paragraphs)
相关推荐
程序员杰哥4 分钟前
软件测试之压力测试详解
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·压力测试
Lhan.zzZ14 分钟前
Qt数据可视化实战:饼图、线图与表格的完整指南
开发语言·qt·信息可视化
Acrelhuang15 分钟前
筑牢用电防线:Acrel-1000 自动化系统赋能 35kV 园区高效供电-安科瑞黄安南
java·大数据·开发语言·人工智能·物联网
今天没有盐19 分钟前
Pandas完全指南:从Series到DataFrame,掌握数据分析核心技能
python·pycharm·编程语言
暴风鱼划水24 分钟前
算法题(Python)数组篇 | 4.长度最小的子数组
python·算法·力扣
小龙报35 分钟前
《算法通关指南数据结构和算法篇(4)--- 队列和queue》
c语言·开发语言·数据结构·c++·创业创新·学习方法·visual studio
民乐团扒谱机42 分钟前
深入浅出理解克尔效应(Kerr Effect)及 MATLAB 仿真实现
开发语言·matlab·光学·非线性光学·克尔效应·kerr effect
B站计算机毕业设计之家1 小时前
大数据python招聘数据分析预测系统 招聘数据平台 +爬虫+可视化 +django框架+vue框架 大数据技术✅
大数据·爬虫·python·机器学习·数据挖掘·数据分析
7澄11 小时前
深入解析 LeetCode 数组经典问题:删除每行中的最大值与找出峰值
java·开发语言·算法·leetcode·intellij idea
计算衎1 小时前
.c .o .a .elf .a2l hex map 这些后缀文件的互相之间的联系和作用
开发语言·elf·gcc·c/c++·a2l