python 将字符串写入word 格式

  1. 读取word文档
import docx 
#打开demo.docx文档,返回一个Document对象,它有paragraphs属性,时Paragraph对象的列表。
doc = docx.Document('demo.docx')
 
len(doc.paragraphs)
>> 7
 
doc.paragraphs[0].text
>> 'Document Title'
 
doc.paragraphs[1].text
>> 'A plain paragraph with some bold and some italic'
 
#每个Paragraph对象也有一个runs属性,它是Run对象的列表。
len(doc.paragraphs[1].runs)
>> 5
 
#Run对象也有一个text属性,包含那个延续的文本
doc.paragraphs[1].runs[0].text
>> 'A plain paragraph with'

2.写入Word文档

要创建自己的.docx文件,就调用docx.Document,返回一个新的、空白的Word Document对象。
Document对象的add_paragraph()方法将一段新文本添加到文档中,并返回添加的Paragraph对象的引用。
在添加文本之后,向Document对象的save()方法传入一个文件名字符串,将Document对象保存到文件。

import docx
 
doc = docx.Document()
doc.add_paragraph('Hello world!')
 
paraObj1 = doc.add_paragraph('This is a second paragraph.')
paraObj2 = doc.add_paragraph('This is a yet another paragraph.')
 
paraObj1.add_run('This text is being added to the second paragraph.')
 
doc.save('multipleParagraphs.docx')

参考:
https://blog.csdn.net/qq_22521211/article/details/81742887?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2allfirst_rank_v2~rank_v25-1-81742887.nonecase

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值