from docx import Document #初始化对象
from docx.shared import Inches #定义英尺
from docx.shared import Pt #定义像素大小
from docx.enum.text importWD_ALIGN_PARAGRAPHfrom docx.oxml.ns import qn #定义style的
from docx.shared importRGBColor#打开docx文件
document =Document()#增加一段
paragraph = document.add_paragraph('This is a demo.')#在段落前直接插入一个新段落
prior_paragraph = paragraph.insert_paragraph_before('welcome!')#这一类属性,每个有三种状态#True 为使用属性;False 为不使用属性;None 默认属性继承自上一个字体
paragraph =document.add_paragraph()
paragraph.add_run('Lorem ipsum')
run= paragraph.add_run('dolor')
run.bold=True
run.font.name=u'宋体'r=run._element
r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
paragraph.add_run('hello').underline =True
paragraph.add_run(u'斜体、').italic =True
paragraph.add_run(u'设置中文字体,')
paragraph.add_run(u'设置字号').font.size=Pt(24)#添加文本
p = document.add_paragraph('test')#文本居中#WD_ALIGN_PARAGRAPH 存储了多种对齐格式#例如:WD_ALIGN_PARAGRAPH.LEFT,左对齐;WD_ALIGN_PARAGRAPH.RIGHT,右对齐
p.alignment =WD_ALIGN_PARAGRAPH.CENTER#左缩进
p.left_indent = Inches(0.3)#首行缩进
p.first_line_indent = Inches(0.3)#上行间距
p.space_before = Pt(18)#下行间距
p.space_after = Pt(12)#添加标题
document.add_heading('The REAL meaning of the universe')
document.add_heading('The role of dolphins', level = 2)#添加引用
document.add_paragraph('Intese quote',style="Intense Quote")#添加分页符
document.add_page_break()#添加表
table = document.add_table(rows=2,cols=2)
cell=table.cell(0,0)
cell.text= 'cell_00'table.cell(0,1).text = 'cell_01'row= table.rows[1]
row.cells[0].text= 'cell_10'row.cells[1].text = 'cell_11'
#行列计数
row_count =len(table.rows)
col_count=len(table.columns)#添加图片
document.add_picture('1.png',width=Inches(1.25))#应用字符样式
paragraph = document.add_paragraph('Normal text,')
paragraph.add_run('text with emphasis','Emphasis')#增加有序列表
document.add_paragraph(
u'有序列表元素1',style='List Number')
document.add_paragraph(
u'有序列表元素2',style='List Number')#增加无序列表
document.add_paragraph(
u'无序列表元素1',style='List Bullet')
document.add_paragraph(
u'无序列表元素2',style='List Bullet')#或者paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.')#paragraph.style = 'ListBullet'
document.save('test.docx')