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)
相关推荐
coding随想4 分钟前
掌控网页的魔法之书:JavaScript DOM的奇幻之旅
开发语言·javascript·ecmascript
Norvyn_713 分钟前
LeetCode|Day18|20. 有效的括号|Python刷题笔记
笔记·python·leetcode
爱吃烤鸡翅的酸菜鱼23 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
chao_78931 分钟前
更灵活方便的初始化、清除方法——fixture【pytest】
服务器·自动化测试·python·pytest
心情好的小球藻1 小时前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
都叫我大帅哥1 小时前
LangChain加载HTML内容全攻略:从入门到精通
python·langchain
惜.己1 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
Y4090011 小时前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
都叫我大帅哥3 小时前
Python的Optional:让你的代码优雅处理“空值”危机
python
曾几何时`5 小时前
基于python和neo4j构建知识图谱医药问答系统
python·知识图谱·neo4j