一.python-docx
这是一个很强大的包,可以用来创建docx文档,包含段落、分页符、表格、图片、标题、样式等几乎所有的word文档中能常用的功能都包含了,这个包的主要功能便是用来创建文档,相对来说用来修改功能不是很强大。
安装
pip install python-docx
新建文档
from docx import Document
document = Document()
添加段落
from docx import Document
document = Document()
paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.')
document.save('00.docx')
#添加段落2
# from docx import Document
#
# document = Document()
# paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.')
# document.add_paragraph('Lorem ipsum dolor sit amet.', style='ListBullet')
# prior_paragraph = paragraph.insert_paragraph_before('Lorem ipsum')
# document.save('00.docx')
添加标题
from docx import Document
document = Document()
document.add_heading('The REAL meaning of the universe',0)
document.add_heading('The role of dolphins', level=0)
document.add_heading('The role of dolphins', level=1)
document.add_heading('The role of dolphins', level=2)
document.add_heading('The role of dolphins', level=3)
document.add_heading('The role of dolphins', level=4)
document.save('00.docx')
新起一页
document.add_page_break()
添加表格
from docx import Document
document = Document()
##创建带边框的表格
table = document.add_table(rows=2, cols=2,style='Table Grid')
cell = table.cell(0, 1)
#第一行第二列
cell.text = 'parrot, possibly dead'
document.save('00.docx')
# from docx import Document
#
# document = Document()
# ##创建带边框的表格
# table = document.add_table(rows=2, cols=2,style='Table Grid')
# #第二行
# row = table.rows[1]
# row.cells[0].text = 'Foo bar to you.'
# row.cells[1].text = 'And a hearty foo bar to you too sir!'
#
# document.save('00.docx')
from docx import Document
#
# document = Document()
#
#
# ##创建带边框的表格
# table = document.add_table(1, 3,style='Table Grid')
# #设置表格样式
# table.style = 'LightShading-Accent1'
# # populate header row
# heading_cells = table.rows[0].cells
# heading_cells[0].text = 'Qty'
# heading_cells[1].text = 'SKU'
# heading_cells[2].text = 'Description'
#
# # add a data row for each item
# for i in range(2):
# cells = table.add_row().cells
# cells[0].text = str(i)
# cells[1].text = str(i)
# cells[2].text = str(i)
# document.save('00.docx')