python读取word指定内容_Python操作word

### 1.Python写word文档

* 要操作word文档首先需要安装python-docx库;

```

pip install python-docx

```

* 然后导入docx模块,或者从docx模块中导入Document类;

```

from docx import Document

```

* 然后使用`Document()`创建一个word文档,若指定路径则是打开文档;

```

document = Document()

```

* 接着就可以在文档中插入内容,比如插入标题可以使用`add_heading()`方法,其中参数level是标题等级,0表示一级标题,1表示二级标题,以此类推。

插入段落可以使用`add_paragraph()`方法,参数style是样式,默认不应用样式。

还有其他例如`add_picture()`方法用来插入图片,add_table()方法插入表格等。

最后和操作Excel一样在文档中添加完内容之后需要使用`save('文件名')`方法保存文档;

大家可以自己查看官网:[https://python-docx.readthedocs.io/en/latest/](https://python-docx.readthedocs.io/en/latest/)

```

from docx import Document

document = Document()

# 插入一级标题

document.add_heading('古诗词', level=0) #插入标题

# 添加段落

p = document.add_paragraph('''

人生就是一场抵达,我们总以为来日方长,可来日并不方长,我们总是在向往明天,而忽略了一个个今天,我们总是在仰望天空,却忘记要走好脚下的路。

''',)

# 插入二级标题

document.add_heading('春夜喜雨', level=1, )

# 插入段落

document.add_paragraph('好雨知时节,当春乃发生。', style='ListNumber')

document.add_paragraph('随风潜入夜,润物细无声。', style='ListNumber')

document.add_paragraph('野径云俱黑,江船火独明。', style='ListNumber')

document.add_paragraph('晓看红湿处,花重锦官城。', style='ListNumber')

# 保存文档

document.save('article.docx')

```

### 2.Python读word文档

* 要读取word文档需要在`Document()`中添加文档路径,用来打开文档;

* 打开文档之后就可以根据需求读取文档,如paragraphs是读取文档段落,tables读取文档表格集等;

* 在已有的文档中追加内容和写入文档一样,最后也要通过`save()`方法保存文档;

```

from docx import Document

document = Document('./article.docx')

# 将word文档的内容一行一行的读取

for paragraph in document.paragraphs:

print(paragraph.text)

document.add_paragraph('恭喜发财', style='ListNumber')

# 保存文档

document.save('new_artical.docx')

```

参考:[https://www.9xkd.com/user/plan-view.html?id=2265170280](https://www.9xkd.com/user/plan-view.html?id=2265170280)

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/69908432/viewspace-2649918/,如需转载,请注明出处,否则将追究法律责任。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值