QZQ的小世界!

  • 首页
你好!
这里是QZQ的博客站!
  1. 首页
  2. 未分类
  3. 正文

使用 python 编辑 docx 文件之Python-docx

2025年4月4日 48点热度 0人点赞 0条评论

python-docx — python-docx 1.1.0 documentation 官方文档

网友的文章:

python操作word——python-docx和python-docx-template模块-CSDN博客

使用Python处理Word文件_python处理word文档-CSDN博客

python使用docx模块读写docx文件的方法与docx模块常用方法_docx.document-CSDN博客

Intro

安装

pip install python-docx

结构

在python-docx模块中,将Word文件结构分成3层:

  • Document:最高层,代表整个Word文件。

  • Paragraph:一个Word文件由许多段落组成,在Python中,整份文件的定义是Document,这些段落的定义就是Paragraph对象。在Python中,一个段落代表一个Paragraph对象,所有段落以Paragraph对象列表方式存在。

  • Run:Word文件要考虑的有字号、字体样式、色彩等,统称为样式。一个Run对象指的是Paragraph对象中相同样式的连续文字,如果文字发生样式变化,Python将以新的Run对象代表。

读取

一般读取

import docx  # 导入docx模块

# 1.创建docx对象
document = docx.Document('test.docx')

# 2.获得Paragraph和Run数量
# 使用len()方法获得Paragraph数量
paragraph_count = len(document.paragraphs)
print(f'段落数:{paragraph_count}')
for i in range(0, paragraph_count):
    # 获取Paragraph的Run数量
    paragraph_run_count = len(document.paragraphs[i].runs)  # i为Paragraph编号
    print(document.paragraphs[i].text)  # 打印Paragraph内容
    print(document.paragraphs[i].runs[i].text)  # 打印第i段第i个Run内容

以上的方法适用于只有文本对象的word文档,文本文档在python-docx模块中会被分为一个个的paragraph对象(可以理解没经过换行的一行就叫一个paragraph),其中如果有格式变化,则会衍生出一个run,run是python-docx模块中最小的一个文本格式单位。

读取表格

用一般读取的方法读取不了表格

当python-docx读取了一个word文档后,表格会以一种不同于paragraph的新的形式,也就是table类被进行储存,遍历表格的方法是:


document = docx.Document('xxxx.docx')

for table in document.tables:
    for row in table.rows:
        for cell in row.cells:
                        print(cell.text)

写入

写入标题

示例如下:

# 设置文档标题,中文要用unicode字符串
document.add_heading(u'我的一个新文档',0)

查看源码可以发现,其实就是一个封装了的写入paragraph

def add_heading(self, text: str = "", level: int = 1):
        """Return a heading paragraph newly added to the end of the document.

        The heading paragraph will contain `text` and have its paragraph style
        determined by `level`. If `level` is 0, the style is set to `Title`. If `level`
        is 1 (or omitted), `Heading 1` is used. Otherwise the style is set to `Heading
        {level}`. Raises |ValueError| if `level` is outside the range 0-9.
        """
        if not 0 <= level <= 9:
            raise ValueError("level must be in range 0-9, got %d" % level)
        style = "Title" if level == 0 else "Heading %d" % level
        return self.add_paragraph(text, style)

写入基本内容

document=docx.Document() # 创建一个空白文档
document.styles['Normal'].font.name = '宋体' # 设置西文字体
document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体') # 设置中文字体

p = document.add_paragraph() # 添加一个段落
p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY # 设置对齐方式
p.paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE # 设置行间距
p.paragraph_format.space_after = Pt(0) # 设置段后间距

run = p.add_run('content') # 延长段落
run.font.color.rgb = RGBColor(255, 0, 0) # 设置字体颜色
run.font.size = Pt(22) # 设置字号,单位是磅
run.font.bold = True # 设置下划线

写入表格

【Python自动化】Python-docx基础入门--插入table表格样式设置_python没有from docx.enum.table import wd_align_verti-CSDN博客

用该代码遍历生成一个包含所有表格内容的文件

from docx.enum.style import WD_STYLE_TYPE
from docx import *

# 生成所有表样式
document = Document()
styles = document.styles

for s in styles:
    if s.type == WD_STYLE_TYPE.TABLE:
        document.add_paragraph("表格样式 : "+ s.name)
        table = document.add_table(3,3, style = s)
        heading_cells = table.rows[0].cells
        heading_cells[0].text = '第一列内容'
        heading_cells[1].text = '第二列内容'
        heading_cells[2].text = '第三列内容'
        document.add_paragraph("\n")

document.save('table_style.docx')

复制

Python docx 删除、复制paragraph以及行高设置和图片插入_python-docx复制操作-CSDN博客

去网上翻了一下,发现了一个拷贝paragraphs的的代码

def copy_para_data(doc_obj, paragraph):
    output_para = doc_obj.add_paragraph()
    for run in paragraph.runs:
        # 简单来说就是进行所有属性的对齐
        output_run = output_para.add_run(run.text)
        output_run.bold = run.bold
        output_run.italic = run.italic
        output_run.underline = run.underline
        output_run.font.color.rgb = run.font.color.rgb
        output_run.style.name = run.style.name
    output_para.paragraph_format.alignment = paragraph.paragraph_format.alignment

另外的办法

python将一个word文档中内容全部复制,添加到另一个word文档末_python复制word到另一个word-CSDN博客

【NLP】word复制指定内容到新的word文档_pythondocx复制内容到另一个word-CSDN博客

去网上找了一下,发现还有一种利用另外模块实现完美word复制的方法,和Python-docx完全不同,先马住。

from win32com.client import Dispatch,DispatchEx
import win32com
import win32com.client
import os

path = os.getcwd()
file_mode = path + r'\第一个文档.docx'
# document = Document(file_mode)
# # 读取word中的所有表格
# tables = document.tables
# document.tables[1].add_row()
app =win32com.client.Dispatch('Word.Application')
# 打开word,经测试要是绝对路径
doc = app.Documents.Open(file_mode)
# 复制word的所有内容
doc.Content.Copy()
# 关闭word
doc.Close()

word = win32com.client.DispatchEx('Word.Application')

doc1 = word.Documents.Open(path + r'\第二个文档.docx')
# myRange = doc1.Range(doc1.Content.End-1, doc1.Content.End-1)

# doc1.Range().Select()
#
# doc.myRange.Selection.Paste()
s = word.Selection
s.MoveRight(1, doc1.Content.End) # 将光标移动到文末,就这一步试了我两个多小时
s.Paste()
doc1.Close()

[文章导入自 http://qzq-go.notion.site/0c279c2afba34bc3b9b372795d33cd24 访问原文获取高清图片]

本作品采用 知识共享署名-非商业性使用 4.0 国际许可协议 进行许可
标签: IT技术 Python 零碎 python 小知识
最后更新:2025年4月3日

QZQ

一只涉猎广泛的技术爱好者,绝赞养猫中~

点赞
< 上一篇
下一篇 >

归档

  • 2025 年 4 月
  • 2025 年 3 月
  • 2025 年 2 月
  • 2025 年 1 月
  • 2024 年 12 月
  • 2024 年 11 月

分类

  • 技术
  • 未分类

COPYRIGHT © 2024 QZQ的小世界!. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang