python
主页 > 脚本 > python >

Python实现自动化批量调整Word样式

2024-12-19 | 佚名 | 点击:

处理大量的Word文档是一个常见的任务,尤其是需要批量修改文档的样式时,手动操作既费时又容易出错。幸运的是,Python提供了丰富的库,可以帮助自动化这一过程。本文将详细介绍如何使用Python批量修改Word文档的样式,并包含具体的示例代码,帮助更高效地完成这一任务。

环境准备

在开始编写代码之前,需要确保已安装Python(本文使用Python 3),并安装了处理Word文档所需的库python-docx。

可以使用以下命令安装python-docx库:

1

pip install python-docx

基本操作

打开和读取Word文档

以下是一个简单的示例,展示如何使用python-docx打开并读取Word文档的内容:

1

2

3

4

5

6

7

8

from docx import Document

 

# 打开Word文档

doc = Document('example.docx')

 

# 读取文档内容

for paragraph in doc.paragraphs:

    print(paragraph.text)

在这个示例中,使用Document类打开一个名为example.docx的Word文档,并遍历文档中的每个段落,打印其文本内容。

修改段落样式

接下来,将展示如何修改段落的样式。假设想将所有段落的字体设置为Arial,字号设置为12。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

from docx.shared import Pt

from docx.oxml.ns import qn

from docx.oxml import OxmlElement

 

def set_paragraph_style(paragraph):

    run = paragraph.runs[0]

    run.font.name = 'Arial'

    run.font.size = Pt(12)

 

    # 设置中文字体

    r = run._element

    rPr = r.get_or_add_rPr()

    eastAsia = OxmlElement('w:eastAsia')

    eastAsia.set(qn('w:val'), '宋体')

    rPr.append(eastAsia)

 

# 打开Word文档

doc = Document('example.docx')

 

# 修改所有段落的样式

for paragraph in doc.paragraphs:

    set_paragraph_style(paragraph)

 

# 保存修改后的文档

doc.save('modified_example.docx')

在这个示例中,定义了一个函数set_paragraph_style,用于设置段落的字体和字号,并遍历文档中的每个段落,调用该函数修改样式。最后,将修改后的文档保存为modified_example.docx。

批量处理Word文档

为了批量处理多个Word文档,可以将上述代码封装到一个函数中,并遍历指定目录下的所有Word文档,进行样式修改。

批量修改文档样式的函数

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

import os

from docx import Document

from docx.shared import Pt

from docx.oxml.ns import qn

from docx.oxml import OxmlElement

 

def set_paragraph_style(paragraph):

    run = paragraph.runs[0]

    run.font.name = 'Arial'

    run.font.size = Pt(12)

 

    # 设置中文字体

    r = run._element

    rPr = r.get_or_add_rPr()

    eastAsia = OxmlElement('w:eastAsia')

    eastAsia.set(qn('w:val'), '宋体')

    rPr.append(eastAsia)

 

def process_word_file(file_path):

    doc = Document(file_path)

    for paragraph in doc.paragraphs:

        set_paragraph_style(paragraph)

    new_file_path = os.path.join('modified_files', os.path.basename(file_path))

    doc.save(new_file_path)

 

def batch_process_word_files(directory):

    if not os.path.exists('modified_files'):

        os.makedirs('modified_files')

 

    for filename in os.listdir(directory):

        if filename.endswith('.docx'):

            file_path = os.path.join(directory, filename)

            process_word_file(file_path)

            print(f"已处理文件: {file_path}")

 

if __name__ == "__main__":

    directory = 'word_files'

    batch_process_word_files(directory)

在这个示例中,定义了以下几个函数:

set_paragraph_style(paragraph):设置段落的字体和字号。

process_word_file(file_path):处理单个Word文档,修改其样式并保存到新的目录。

batch_process_word_files(directory):批量处理指定目录下的所有Word文档,并将修改后的文档保存到modified_files目录。

运行批量处理脚本

将上述代码保存为batch_modify_word_styles.py,然后在命令行中运行:

1

python batch_modify_word_styles.py

确保在脚本运行前,将需要处理的Word文档放在word_files目录中。脚本运行后,修改后的文档将保存到modified_files目录。

示例:修改不同类型的样式

除了修改段落样式,还可以修改标题、表格和图片的样式。

修改标题样式

1

2

3

4

5

6

7

8

9

10

11

12

13

14

def set_heading_style(paragraph):

    if paragraph.style.name.startswith('Heading'):

        run = paragraph.runs[0]

        run.font.name = 'Arial'

        run.font.size = Pt(14)

        run.bold = True

 

def process_word_file_with_headings(file_path):

    doc = Document(file_path)

    for paragraph in doc.paragraphs:

        set_paragraph_style(paragraph)

        set_heading_style(paragraph)

    new_file_path = os.path.join('modified_files', os.path.basename(file_path))

    doc.save(new_file_path)

修改表格样式

1

2

3

4

5

6

7

8

9

10

11

12

13

14

def set_table_style(table):

    for row in table.rows:

        for cell in row.cells:

            for paragraph in cell.paragraphs:

                set_paragraph_style(paragraph)

 

def process_word_file_with_tables(file_path):

    doc = Document(file_path)

    for paragraph in doc.paragraphs:

        set_paragraph_style(paragraph)

    for table in doc.tables:

        set_table_style(table)

    new_file_path = os.path.join('modified_files', os.path.basename(file_path))

    doc.save(new_file_path)

修改图片样式

修改图片样式通常涉及更复杂的操作,具体实现根据需求而定。

以下是一个简单示例,调整图片大小:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

from docx.shared import Inches

 

def set_picture_style(document):

    for paragraph in document.paragraphs:

        for run in paragraph.runs:

            for inline_shape in run.inline_shapes:

                inline_shape.width = Inches(2)

                inline_shape.height = Inches(2)

 

def process_word_file_with_pictures(file_path):

    doc = Document(file_path)

    for paragraph in doc.paragraphs:

        set_paragraph_style(paragraph)

    set_picture_style(doc)

    new_file_path = os.path.join('modified_files', os.path.basename(file_path))

    doc.save(new_file_path)

总结

本文详细介绍了如何使用Python批量修改Word文档的样式。通过使用python-docx库,我们可以打开、读取和修改Word文档中的段落、标题、表格和图片样式。文章首先展示了基本操作,包括打开文档和修改段落样式,然后进一步介绍了如何批量处理多个Word文档。最后,还提供了修改标题、表格和图片样式的示例代码。掌握这些技巧,可以显著提升办公效率,实现对文档的自动化处理

原文链接:
相关文章
最新更新