分享

python 读写 docx...

 大傻子的文渊阁 2021-04-05

1、打开一个doc文档

  1. import docx
  2. from docx import Document
  3. doc = Document(file_path)

2、新建一个doc文档

  1. # 新建doc文档
  2. doc = docx.Document()

3、设置doc文档格式

  1. # 将正文英文字体设置成
  2. doc.styles['Normal'].font.name = u'Times New Roman'
  3. # 将正文中文字体设置成宋体
  4. doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
  5. # 获取正文样式
  6. style = doc.styles['Normal']
  7. # 获取段落样式
  8. paragraph_format = style.paragraph_format
  9. # 首行缩进0.74厘米,即2个字符
  10. paragraph_format.first_line_indent = Cm(0.74)
  11. # 设置1级标题的字体为Times New Roman, 且无缩进
  12. # 这种写法只能够修改Normal样式的字体,修改标题的字体无效。
  13. style_heading1 = doc.styles['Heading 1']
  14. style_heading1.font.name = u'Times New Roman'
  15. heading1_format = style_heading1.paragraph_format
  16. heading1_format.first_line_indent = Cm(0)
  17. # 设置2级标题的字体为Times New Roman, 且无缩进
  18. style_heading2 = doc.styles['Heading 2']
  19. style_heading2.font.name = 'Times New Roman'
  20. heading2_format = style_heading2.paragraph_format
  21. heading2_format.first_line_indent = Cm(0)

4、向docx文档写入内容

  1. # 写入一级标题
  2. doc.add_heading(dashboard, 1)
  3. # 写入二级标题
  4. doc.add_heading(visualization, 2)
  5. # 写入 段落文字
  6. doc.add_paragraph('该visualization的类型为' + visualization_type + ',其作用是' + description + '。其界面如下图所示:', style='Body Text')
  7. # 写入图片
  8. # 指定图片宽度为 4英寸, 图片高度会自动调整
  9. doc.add_picture(pic_path, width=Inches(4))
  10. last_paragraph = doc.paragraphs[-1]
  11. #图片居中设置
  12. last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
  13. # 保存文档
  14. doc.save('resource/output.docx')

 

2、获取 paragraph的内容, doc.paragrashs是一个列表,遍历列表分别获取每一个段落的内容:

  1. for j, paragraph in enumerate(doc.paragraphs):
  2. para_text = paragraph.text

标题也属于doc.paragrashs列表。

判断某个段落是否是标题:

paragraph.style.name == 'Heading 3'

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多