怎么在Python中利用python-docx对word文档进行读写?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
一、安装包
pip3 install python-docx
二、创建word文档
下面是在官文示例基础上对个别地方稍微修改,并加上函数的使用说明
from docx import Document from docx.shared import Inches document = Document() #添加标题,并设置级别,范围:0 至 9,默认为1 document.add_heading('Document Title', 0) #添加段落,文本可以包含制表符(\t)、换行符(\n)或回车符(\r)等 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='Intense Quote') #添加项目列表(前面一个小圆点) document.add_paragraph( 'first item in unordered list', style='List Bullet' ) document.add_paragraph('second item in unordered list', style='List Bullet') #添加项目列表(前面数字) document.add_paragraph('first item in ordered list', style='List Number') document.add_paragraph('second item in ordered list', style='List Number') #添加图片 document.add_picture('monty-truth.png', width=Inches(1.25)) records = ( (3, '101', 'Spam'), (7, '422', 'Eggs'), (4, '631', 'Spam, spam, eggs, and spam') ) #添加表格:一行三列 # 表格样式参数可选: # Normal Table # Table Grid # Light Shading、 Light Shading Accent 1 至 Light Shading Accent 6 # Light List、Light List Accent 1 至 Light List Accent 6 # Light Grid、Light Grid Accent 1 至 Light Grid Accent 6 # 太多了其它省略... table = document.add_table(rows=1, cols=3, style='Light Shading Accent 2') #获取第一行的单元格列表 hdr_cells = table.rows[0].cells #下面三行设置上面第一行的三个单元格的文本值 hdr_cells[0].text = 'Qty' hdr_cells[1].text = 'Id' hdr_cells[2].text = 'Desc' for qty, id, desc in records: #表格添加行,并返回行所在的单元格列表 row_cells = table.add_row().cells row_cells[0].text = str(qty) row_cells[1].text = id row_cells[2].text = desc document.add_page_break() #保存.docx文档 document.save('demo.docx')
创建的demo.docx内容如下:
三、读取word文档
from docx import Document doc = Document('demo.docx') #每一段的内容 for para in doc.paragraphs: print(para.text) #每一段的编号、内容 for i in range(len(doc.paragraphs)): print(str(i), doc.paragraphs[i].text) #表格 tbs = doc.tables for tb in tbs: #行 for row in tb.rows: #列 for cell in row.cells: print(cell.text) #也可以用下面方法 '''text = '' for p in cell.paragraphs: text += p.text print(text)'''
运行结果:
Document Title A plain paragraph having some bold and some italic. Heading, level 1 Intense quote first item in unordered list second item in unordered list first item in ordered list second item in ordered list Document Title A plain paragraph having some bold and some italic. Heading, level 1 Intense quote first item in unordered list second item in unordered list first item in ordered list second item in ordered list Qty Id Desc 101 Spam 422 Eggs 631 Spam, spam, eggs, and spam [Finished in 0.2s]
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。