python专题操作word

一 前言

word的操作也是经常必备的技能之一,今天有空整理了一份给大家!!加油哟!!
公众号:知识追寻者

知识追寻者(Inheriting the spirit of open source, Spreading technology knowledge;)

二 操作Word

安装 python-docx

pip install python-docx

2.1 读取word

word 中的存档格式 为 一个 Document 对象; 每个Document对象 包含许多 Paragraph对象 和 table 对象;其中 Paragraph 对象 有许多行内元素 Run 对象; Run对象 又有 字体(font),数据(text),颜色(color),字号(size)等对象;table对象比较简单,可以跟excel联系起来,就是由 行(row)列(column)组成;

读取每段内容示例

from docx import Document

path = r'C:\mydata\generator\py\tt.docx'
# 获取Document对象
doc = Document(path)
# 读取每段
contents = [ paragraph.text for paragraph in doc.paragraphs]
# 读取每行
for line in contents:
    print(line)

Tip : 读取时值读取段落文本内容,其它内容不会被读取进段落

读取表格示例

from docx import Document
path = r'C:\mydata\generator\py\tt.docx'
# 获取Document对象
doc = Document(path)
# 获取所有表格
tables = [table for table in doc.tables]
 for row in table.rows:
        for cell in row.cells:
            # 遍历每个单元格内容
            text = str(cell.text)

Tip: 读取的是整个word的表格的单元格内容

2.2 写入word

主要方法如下

  1. Document(); 新建空白文档对象;
  2. add_heading(text, level=1) ; 写入 标题 text 是内容,leve 是标题等级 0-9;
  3. add_paragraph(text, style);添加段落描述;text,是内容,styles设置风格
  4. add_paragraph(text, style).add_run( text, style);为段落添加行,text,是内容,styles设置风格;
  5. add_picture(image_path_or_stream, width, height);分别是图片地址,宽度,高度;
  6. add_page_break();插入分页符
  7. add_table(rows, cols, style); 参数分别是 行数,列数,风格;
  8. add_table(rows, cols, style).rows() ;行数
  9. add_table(rows, cols, style).cols() ;列数

示例代码

from docx import Document
from docx.shared import Pt
from docx.shared import Inches
from docx.oxml.ns import qn
from docx.shared import RGBColor

# 新建空白文档
docx = Document()
# 创建标题
docx.add_heading('知识追寻者操作word',0)

# 创建一级标题
docx.add_heading('写入段落示例',1)
# 添加段落描述
docx.add_paragraph('知识追寻者(Inheriting the spirit of open source, Spreading technology knowledge;)')

# 写入一级标题
docx.add_heading('写入行示例',1)
# 写入行
run = docx.add_paragraph('公众号:知识追寻者').add_run('快点关注吧')
# 设置字体大小
run.font.size = Pt(18)
# 设置字体
run.font.name='黑体'
# 设置字体颜色
run.font.color.rgb = RGBColor(0xFF, 0x00, 0x00)
# 设置粗体
run.bold = True
# 设置斜体
run.italic = True

docx.add_heading('写入无序列表',2)
docx.add_paragraph(
    '你是圆的啊!', style='List Bullet'
)
docx.add_heading('写入有序列表',2)
docx.add_paragraph(
    '你是方的啊!', style='List Number'
)

docx.add_heading('写入表格',1)
# 新建1行3列的表
table = docx.add_table(rows=1, cols=3)
# 添加表头
cells = table.rows[0].cells
cells[0].text = '编号'
cells[1].text = '姓名'
cells[2].text = '性别'
# 表格数据
records = ( (1, 'carry', 'girl'), (2, 'cherry', 'girl'), (3, 'bafei', 'boy'))
# 将表格数据加入表格
for id, name, gender in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(id)
    row_cells[1].text = name
    row_cells[2].text = gender


docx.add_heading('写入图片',1)
docx.add_picture('zszxz.jpg', width=Inches(1.0))

# 保存文件
docx.save('zszxz.docx')

结果

三 参考文档

功能多内容参照官方文档

官方文档

关注知识追寻者:
tLeP2D.png

猜你喜欢

转载自blog.csdn.net/youku1327/article/details/105775518