Python python-docx 读写 word

____tz_zs

https://python-docx.readthedocs.io/en/latest/

python-docx模块处理word文档,处理方式是面向对象的。也就是说python-docx模块会把word文档,文档中的段落、文本、字体等都看做对象,对象进行处理就是对word文档的内容处理。

如果需要读取word文档中的文字(一般来说,程序也只需要认识word文档中的文字信息),需要先了解python-docx模块的几个概念。

 

  • Document对象,表示一个word文档。
  • Paragraph对象,表示word文档中的一个段落
  • Paragraph对象的text属性,表示段落中的文本内容。

·

安装python-docx库

pip install python-docx

·

使用

·

# -*- coding: utf-8 -*-
"""
@author: tz_zs
"""

import docx

# 读取文件
document = docx.Document('./kk011.docx')
# 总共有多少段落
print('总共有 {} 个段落'.format(len(document.paragraphs)))
for paragraph in document.paragraphs:  # 遍历paragraph对象的列表
    # paragraph 为每个段落的对象 docx.text.paragraph.Paragraph object

    text = paragraph.text  # 每一段的文字内容
    print(text)

·

官方文档Demo——创建word文件

# -*- coding: utf-8 -*-
"""
@author: tz_zs
"""
from docx import Document
from docx.shared import Inches

document = Document()

document.add_heading('Document Title', 0)

p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')

document.add_paragraph(
    'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
    'first item in ordered list', style='ListNumber'
)

document.add_picture('monty-truth.png', width=Inches(1.25))

table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
# for item in recordset:
#     row_cells = table.add_row().cells
#     row_cells[0].text = str(item.qty)
#     row_cells[1].text = str(item.id)
#     row_cells[2].text = item.desc

document.add_page_break()

document.save('demo.docx')

·

 

你可能感兴趣的:(#,综合,Python,word,python-docx)