提要:
document.add_paragraph() 创建段落、
insert_paragraph_before 插入段落、
document.add_table() 创建表格
document.add_picture() 创建图片
首先导入相关包:
import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH #设置对象居中、对齐等。
from docx.enum.text import WD_TAB_ALIGNMENT,WD_TAB_LEADER #设置制表符等
from docx.shared import Inches #设置图像大小
from docx.shared import Pt #设置像素、缩进等
from docx.shared import RGBColor #设置字体颜色
from docx.shared import Length #设置宽度
下面开始操作涉及(页眉、标题、段落、字体、样式) 以及 (表格) 以及 (图片)。
首先创建一个空白文档类,也可传入文件名打开已有文档
document=docx.Document()
#新增页眉
section=document.sections[0]
header=section.header
bt1=header.paragraphs[0]
bt1.text='此处是页眉1'
#新增头信息
t1=document.add_paragraph('此处Tetle信息','Title')
#新增段落 及 向前插入段落
p1=document.add_paragraph('新增段落P1')
pin1=p1.insert_paragraph_before('在p1前插入段落pin1')
#段落里设置参数样式 或 指定.style来设置参数
p2=document.add_paragraph('新增段落p2并设置style类型',style='ListBullet')
p3=document.add_paragraph('新增段落p3并指定style类型')
p3.style='ListBullet'
#添加标题 可设置标题级别1-9
h1=document.add_heading('此处默认标题1')
h2=document.add_heading('此处添加标题2',level=2)
h3=document.add_heading('此处添加标题3',level=3)
#通过.add_run来设置字体: 加粗、斜体、大小、颜色、下划线等。
paragraph=document.add_paragraph()
r1=paragraph.add_run('通过.bold=True来设置粗体')
r1.bold=True
r1.style='Emphasis'
r2=paragraph.add_run('也可以')
r3=paragraph.add_run('\n通过.italic=True来设置斜体,\n通过.font.size来设置字体大小,\n通过.font.color.rgb=RGBColor来设置字体颜色')
r3.italic=True
r3.font.size=Pt(20)
r3.font.color.rgb=RGBColor(200,77,150)
# =============================================================================
# all_caps => 全部大写字母
# bold => 加粗
# color => 字体颜色
# complex_script => 是否为“复杂代码”
# cs_bold => “复杂代码”加粗
# cs_italic => “复杂代码”斜体
# double_strike => 双删除线
# emboss => 文本以凸出页面的方式出现
# hidden => 隐藏
# imprint => 印记
# italic => 斜体
# name => 字体
# no_proof => 不验证语法错误
# outline => 显示字符的轮廓
# shadow => 阴影
# small_caps => 小型大写字母
# snap_to_grid => 定义文档网格时对齐网络
# strike => 删除线
# subscript => 下标
# superscript => 上标
# underline => 下划线
# =============================================================================
#设置居中、左右对齐、缩进、制表符等
p4=document.add_paragraph('准备开始设置居中、左右对齐、缩进等')
p4.paragraph_format.alignment=WD_ALIGN_PARAGRAPH.CENTER
# =============================================================================
# # LEFT 左对齐
# # CENTER 文字居中
# # RIGHT 右对齐
# # JUSTIFY 本两端对齐
# =============================================================================
#设置缩进,默认Inches(0.5)等于四个空格
p5=document.add_paragraph('准备开始设置缩进、段落间距、段落行距\n盖闻:人生在世,富贵不能淫,贫贱不能移。文章盖世,孔子厄于陈邦;武略超群,太公钓于渭水。颜渊命短,殊非凶恶之徒;盗跖年长,岂是善良之辈。尧帝明圣,却生不肖之儿;瞽叟愚顽,反生大孝之子。张良原是布衣,萧何称谓县吏。晏子身无五尺,封作齐国宰相;孔明卧居草庐,能作蜀汉军师。楚霸虽雄,败于乌江自刎;汉王虽弱,竟有万里江山。李广有射虎之威,到老无封;冯唐有乘龙之才,一生不遇。韩信未遇之时,无一日三餐,及至遇行,腰悬三齐玉印,一旦时衰,死于阴人之手。')
p5.paragraph_format.left_indent=Inches(0.5)
#也可以设置首行缩进
p5.paragraph_format.first_line_indent=Inches(0.5)
#设置段落间距 分为段落前 和 段落后
p5.paragraph_format.space_before=Pt(30)
p5.paragraph_format.space_after=Pt(12)
#设置段落行距 当行距为 最小值 和 固定值时,设置值单位是 磅,用Pt;当行间距为 多倍行距 时,设置值为数值。
#p5.paragraph_format.line_spacing=Pt(30)
# =============================================================================
# SINGLE 单倍行距(默认)
# ONE_POINT_FIVE 1.5倍行距
# DOUBLE2 倍行距
# AT_LEAST 最小值
# EXACTLY 固定值
# MULTIPLE 多倍行距
#
# paragraph.line_spacing_rule = WD_LINE_SPACING.EXACTLY #固定值
# paragraph_format.line_spacing = Pt(18) # 固定值18磅
# paragraph.line_spacing_rule = WD_LINE_SPACING.MULTIPLE #多倍行距
# paragraph_format.line_spacing = 1.75 # 1.75倍行间距
# =============================================================================
#分页属性`
#p5.paragraph_format.keep_with_next = True
# =============================================================================
# #widow_control => 孤行控制
# #keep_with_next => 与下段同页
# #page_break_before => 段前分页
# #keep_together => 段中不分页
# =============================================================================
#添加分页符
document.add_page_break()
p5=document.add_paragraph('.add_page_break()硬分页,即使文本未满')
添加表格、设置表格样式
table=document.add_table(rows=2,cols=2)
table.style='LightShading-Accent1'
#选择表格内单元格、单元格赋值添加和改变内容
cell=table.cell(0,1)
cell.text='通过cell.text()来添加内容' #
#选择表格的行,通过索引,然后索引单元格
row=table.rows[1]
row.cells[0].text='通过.add_table(,)来添加表格'
row.cells[1].text='通过for row in table.rows内嵌套 for cell in row.cells来循环输出表格内容'
#for循环逐行输出表格内容
for row in table.rows:
for cell in row.cells:
print(cell.text)
#len表格内行列数
row_count=len(table.rows)
col_count=len(table.columns)
print(row_count,col_count,'现表格行列数')
row=table.add_row() #逐步添加行
print(len(table.rows),len(table.columns),'添加后表格行列数')
#添加另一个表格 及 指定表格样式
table1=document.add_table(1,3)
table1.style='LightShading-Accent2' #设置表格样式
#填充 标题行
heading_cells=table1.rows[0].cells #获取 行列标
heading_cells[0].text='Qtx' #为行列表内的cell单元格 赋值
heading_cells[1].text='Sku'
heading_cells[2].text='Des'
#表格数据
items=(
(7,'1024','plush kitens'),
(3,'2042','furbees'),
(1,'1288','french poodle collars,deluxe')
)
#为每个项目添加数据行
for item in items:
cells=table1.add_row().cells
cells[0].text=str(item[0])
cells[1].text=str(item[1])
cells[2].text=str(item[2])
#添加分页符
document.add_page_break()
添加图片
document.add_picture('002592.png',width=Inches(2))
最后保存文档
document.save('测试文件.docx')
.
.
.
.
.
python-docx模块操作,代码全文如下:
import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH #设置对象居中、对齐等。
from docx.enum.text import WD_TAB_ALIGNMENT,WD_TAB_LEADER #设置制表符等
from docx.shared import Inches #设置图像大小
from docx.shared import Pt #设置像素、缩进等
from docx.shared import RGBColor #设置字体颜色
from docx.shared import Length #设置宽度
#涉及(页眉、标题、段落、字体、样式) 以及 (表格) 以及 (图片)。
#首先创建一个空白文档类,也可传入文件名打开已有文档
document=docx.Document()
#新增页眉
section=document.sections[0]
header=section.header
bt1=header.paragraphs[0]
bt1.text='此处是页眉1'
#新增头信息
t1=document.add_paragraph('此处Tetle信息','Title')
#新增段落 及 向前插入段落
p1=document.add_paragraph('新增段落P1')
pin1=p1.insert_paragraph_before('在p1前插入段落pin1')
#段落里设置参数样式 或 指定.style来设置参数
p2=document.add_paragraph('新增段落p2并设置style类型',style='ListBullet')
p3=document.add_paragraph('新增段落p3并指定style类型')
p3.style='ListBullet'
#添加标题 可设置标题级别1-9
h1=document.add_heading('此处默认标题1')
h2=document.add_heading('此处添加标题2',level=2)
h3=document.add_heading('此处添加标题3',level=3)
#通过.add_run来设置字体: 加粗、斜体、大小、颜色、下划线等。
paragraph=document.add_paragraph()
r1=paragraph.add_run('通过.bold=True来设置粗体')
r1.bold=True
r1.style='Emphasis'
r2=paragraph.add_run('也可以')
r3=paragraph.add_run('\n通过.italic=True来设置斜体,\n通过.font.size来设置字体大小,\n通过.font.color.rgb=RGBColor来设置字体颜色')
r3.italic=True
r3.font.size=Pt(20)
r3.font.color.rgb=RGBColor(200,77,150)
# =============================================================================
# all_caps => 全部大写字母
# bold => 加粗
# color => 字体颜色
# complex_script => 是否为“复杂代码”
# cs_bold => “复杂代码”加粗
# cs_italic => “复杂代码”斜体
# double_strike => 双删除线
# emboss => 文本以凸出页面的方式出现
# hidden => 隐藏
# imprint => 印记
# italic => 斜体
# name => 字体
# no_proof => 不验证语法错误
# outline => 显示字符的轮廓
# shadow => 阴影
# small_caps => 小型大写字母
# snap_to_grid => 定义文档网格时对齐网络
# strike => 删除线
# subscript => 下标
# superscript => 上标
# underline => 下划线
# =============================================================================
#设置居中、左右对齐、缩进、制表符等
p4=document.add_paragraph('准备开始设置居中、左右对齐、缩进等')
p4.paragraph_format.alignment=WD_ALIGN_PARAGRAPH.CENTER
# =============================================================================
# # LEFT 左对齐
# # CENTER 文字居中
# # RIGHT 右对齐
# # JUSTIFY 本两端对齐
# =============================================================================
#设置缩进,默认Inches(0.5)等于四个空格
p5=document.add_paragraph('准备开始设置缩进、段落间距、段落行距\n盖闻:人生在世,富贵不能淫,贫贱不能移。文章盖世,孔子厄于陈邦;武略超群,太公钓于渭水。颜渊命短,殊非凶恶之徒;盗跖年长,岂是善良之辈。尧帝明圣,却生不肖之儿;瞽叟愚顽,反生大孝之子。张良原是布衣,萧何称谓县吏。晏子身无五尺,封作齐国宰相;孔明卧居草庐,能作蜀汉军师。楚霸虽雄,败于乌江自刎;汉王虽弱,竟有万里江山。李广有射虎之威,到老无封;冯唐有乘龙之才,一生不遇。韩信未遇之时,无一日三餐,及至遇行,腰悬三齐玉印,一旦时衰,死于阴人之手。')
p5.paragraph_format.left_indent=Inches(0.5)
#也可以设置首行缩进
p5.paragraph_format.first_line_indent=Inches(0.5)
#设置段落间距 分为段落前 和 段落后
p5.paragraph_format.space_before=Pt(30)
p5.paragraph_format.space_after=Pt(12)
#设置段落行距 当行距为 最小值 和 固定值时,设置值单位是 磅,用Pt;当行间距为 多倍行距 时,设置值为数值。
#p5.paragraph_format.line_spacing=Pt(30)
# =============================================================================
# SINGLE 单倍行距(默认)
# ONE_POINT_FIVE 1.5倍行距
# DOUBLE2 倍行距
# AT_LEAST 最小值
# EXACTLY 固定值
# MULTIPLE 多倍行距
#
# paragraph.line_spacing_rule = WD_LINE_SPACING.EXACTLY #固定值
# paragraph_format.line_spacing = Pt(18) # 固定值18磅
# paragraph.line_spacing_rule = WD_LINE_SPACING.MULTIPLE #多倍行距
# paragraph_format.line_spacing = 1.75 # 1.75倍行间距
# =============================================================================
#分页属性
#p5.paragraph_format.keep_with_next = True
# =============================================================================
# #widow_control => 孤行控制
# #keep_with_next => 与下段同页
# #page_break_before => 段前分页
# #keep_together => 段中不分页
# =============================================================================
#添加分页符
document.add_page_break()
p5=document.add_paragraph('.add_page_break()硬分页,即使文本未满')
#添加表格、设置表格样式
table=document.add_table(rows=2,cols=2)
table.style='LightShading-Accent1'
#选择表格内单元格、单元格赋值添加和改变内容
cell=table.cell(0,1)
cell.text='通过cell.text()来添加内容' #
#选择表格的行,通过索引,然后索引单元格
row=table.rows[1]
row.cells[0].text='通过.add_table(,)来添加表格'
row.cells[1].text='通过for row in table.rows内嵌套 for cell in row.cells来循环输出表格内容'
#for循环逐行输出表格内容
for row in table.rows:
for cell in row.cells:
print(cell.text)
#len表格内行列数
row_count=len(table.rows)
col_count=len(table.columns)
print(row_count,col_count,'现表格行列数')
row=table.add_row() #逐步添加行
print(len(table.rows),len(table.columns),'添加后表格行列数')
#添加另一个表格 及 指定表格样式
table1=document.add_table(1,3)
table1.style='LightShading-Accent2' #设置表格样式
#填充 标题行
heading_cells=table1.rows[0].cells #获取 行列标
heading_cells[0].text='Qtx' #为行列表内的cell单元格 赋值
heading_cells[1].text='Sku'
heading_cells[2].text='Des'
#表格数据
items=(
(7,'1024','plush kitens'),
(3,'2042','furbees'),
(1,'1288','french poodle collars,deluxe')
)
#为每个项目添加数据行
for item in items:
cells=table1.add_row().cells
cells[0].text=str(item[0])
cells[1].text=str(item[1])
cells[2].text=str(item[2])
#添加分页符
document.add_page_break()
#添加图片
document.add_picture('002592.png',width=Inches(2))
document.save('测试文件.docx')
即:
document.add_paragraph() 创建段落、
insert_paragraph_before 插入段落、
document.add_table() 创建表格
document.add_picture() 创建图片
完。