Python修改Word内容

RS 技术•随笔评论853字数 2131阅读7分6秒阅读模式

最近要批量修改Word内容,尝试用Python写一段代码,留存一下。

from docx import Document
import os

#定义了一个modify_header函数来修改单个文档的页眉章节。该函数接受两个参数:document_path是要修改的文档路径,new_section是新的章节内容。
#函数首先打开文档并获取第一个节的页眉内容。然后,它遍历页眉的段落,并将每个段落的文本内容设置为新的章节内容。
def modify_header(document_path, new_section):
    """
    修改文档的页眉章节
    """
    # 获取第一个节的页眉
    section = document.sections[0]
    header = section.header

    # 修改页眉内容
    for paragraph in header.paragraphs:
        paragraph.text = new_section

#定义了一个get_file_names函数,它接受一个路径作为参数,并返回该路径下的文件名列表
def get_file_names(path):
    """
    获取指定路径下的文件名列表
    """
    file_names = []
    for file in os.listdir(path):
        if os.path.isfile(os.path.join(path, file)):
            file_names.append(file)
    return file_names

#定义了一个delete_content函数来删除文档中指定的内容。该函数接受两个参数:document_path是要删除内容的文档路径,content_to_delete是要删除的内容
def delete_content(document_path, content_to_delete):
    """
    删除文档中指定的内容
    """
    
    # 遍历文档的段落
    for paragraph in document.paragraphs:
        if content_to_delete in paragraph.text:
            # 删除包含指定内容
            paragraph.text = ""

    # 遍历文档的表格
    for table in document.tables:
        for row in table.rows:
            for cell in row.cells:
                if content_to_delete in cell.text:
                    # 删除包含指定内容的单元格
                    cell.text = ""


#授课日期列表        
sk_data=[
'2023-04-12',
'2023-04-14',
'2023-04-17',
'2023-04-19',
'2023-04-21',
'2023-04-24',
'2023-04-26',
'2023-04-28',
'2023-05-08',
'2023-05-10',
'2023-05-12',
'2023-05-15',
'2023-05-17',
'2023-05-19',
'2023-05-22',
'2023-05-24',
'2023-05-26',
'2023-05-29',
'2023-05-31',
'2023-06-02',
'2023-06-05',
'2023-06-07',
'2023-06-09',
'2023-06-12',
'2023-06-14',
'2023-06-16',
'2023-06-19',
'2023-06-21',
]

# 指定路径
path = 'H:\\2023.6\\'

# 获取路径下的文件名列表
file_names = get_file_names(path)

# 打印文件名列表,了解目录文件
for file_name in file_names:
    print(path + file_name)


#正式开始修改文件内容:
index=0
for file_name in file_names:
    # 打开包含表格的Word文档
    doc_path = path + file_name
    document = Document(doc_path)

    #修改页眉内容
    new_section="信息技术"
    modify_header(doc_path,new_section)

    #删除指定内容
    content_to_delete="教学设计范例"
    delete_content(doc_path,content_to_delete)

    # 获取第一个表格
    table = document.tables[0]

    # 获取表格的行数和列数
    num_rows=len(table.rows)
    num_columns=len(table.columns)

    # 打印行数和列数
    print(num_rows,num_columns)

    #打印授课日期下单元格内容
    print(table.cell(2,6).text)
    # 修改授课日期表格内容
    row_index = 2
    column_index = 6
    new_value = "2023-4-12"
    table.cell(row_index, column_index).text = sk_data[index]
    #班级
    table.cell(2,5).text="高一计算机"

    # 保存修改后的文档
    output_path = path + file_name
    document.save(output_path)
    index=index+1

继续阅读
 
RS
  • 本文由 RS 发表于 2023年6月26日 08:59:50
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定