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, "幸福")

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

文本

python给word插入脚注_第1张图片

脚注

python给word插入脚注_第2张图片

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)

你可能感兴趣的:(python,word,开发语言)