python-word

读取

开头

pip install python-docx 
from docx import Document #引入
doc = Document('test.docx') #打开

读取段落信息

paragraphs = doc.paragraphs #是个tuple可用len(paragraphs)得到长度
paragraphs[0].text #返回第一段文字

读取文档中的表格信息

tables = doc.tables #是个tuple可用len(tables)得到长度
table0 = tables[0] #获取第一个表格
tables[0].cell(0,0).text #返回第一格的文字
table0.rows[0] #返回第一行
table0.columns[0] #返回第一列

写入

开头

doc = Document()  #新建文档对象
doc.save('test.docx') #保存文档

写入数据

doc.add_heading('标题',1) #给文章增加标题
doc.add_paragraph('第一个段落:') #给文章增加段落
doc.paragraphs[0].add_run('段落文字') #给第一段增加文字
doc.add_table(2,3) #加一个23列的表格
table0.cell(0,0).text = '0' #给第一个表格的第一个单元格写入数据

字体格式

doc.paragraphs[0].runs #返回第一段的所有run(run对象代表段落中相同格式的一段文字)
from docx.oxml.ns import qn 
run_2.font.name = 'Times New Roman' #这一步主要是先设置一下字体名字这个属性
runs[0].font.element.rPr.rFonts.set(qn('w:eastAsia'),'楷体') #设置楷体
from docx.shared import Pt
runs[0].font.size = Pt(14) #设置字体大小
runs[0].font.bold = True #设置加粗
runs[0].font.italic = True #设置斜体
runs[0].font.underline = True #设置下划线
from docx.shared import RGBColor
runs[0].font.color.rgb = RGBColor(255,55,55) #设置颜色

表格格式

from docx.enum.style import WD_STYLE_TYPE
style = doc.styles
for i in style:
    if i.type == WD_STYLE_TYPE.TABLE:
        print(i)
#这样可打印出所有的表格样式
doc.add_table(3,6,style ='Table Grid' ) #创建前设置
table0.style = 'Table Grid' #创建后设置
table0.add_column(shared.Inches(3)) #增加列
table0.add_row() #增加行
table0.cell(2,0).merge(table0.cell(2,1)) #合并单元格

表格内字体设置

cell_par = cell(0,0).paragraphs[0] #获取到对象
from docx.enum.text import WD_ALIGN_PARAGRAPH
cell_par.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER #中心对齐
cell_run = cell_par.runs[0] #获取 run 对象
cell_run.font.name = 'Times New Roman'
from docx.oxml.ns import qn
cell_run.font.element.rPr.rFonts.set(qn('w:eastAsia'),'楷体') #设为楷体
from docx.shared import RGBColor
cell_run.font.color.rgb = RGBColor(255,55,55) #设为红色
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值