zoukankan      html  css  js  c++  java
  • [python-docx]docx文档操作的库

     1 from docx import Document
     2 from docx.shared import Inches
     3 
     4 # 新建document对象
     5 document = Document()
     6 
     7 # 添加段落对象
     8 paragraph = document.add_paragraph("hello world".title())
     9 
    10 # 插入段落
    11 paragraph.insert_paragraph_before("Python")
    12 
    13 # 添加heading
    14 document.add_heading("this is default heading")
    15 
    16 # 添加换页
    17 # document.add_page_break()
    18 
    19 # 添加表格
    20 table = document.add_table(rows=2, cols=3)
    21 table.add_row() #添加行
    22 
    23 for row in table.rows:      # 遍历表格
    24     for cell in row.cells:
    25         cell.text = "fuck"
    26 cell = table.cell(0,0)  #单元格
    27 
    28 # 添加图像并调整大小
    29 document.add_picture("test.gif", width=Inches(1.0))
    30 
    31 # 样式
    32 paragraph = document.add_paragraph("Did i looking better?")
    33 paragraph.style = "ListBullet"
    34 
    35 # run
    36 paragraph = document.add_paragraph("this is before run test ")
    37 run = paragraph.add_run("this is test run")
    38 run.bold = True
    39 run.style = "Emphasis"  # 样式
    40 paragraph.add_run(" run ends hear.")
    41 
    42 # 保存文档
    43 document.save("test.docx")

    以上是新建docx文档

    1 from docx import Document
    2 
    3 # 创建文档对象(不用关闭)
    4 document = Document("net1.exe.docx")
    5 
    6 # 遍历段落
    7 with open("test.txt", 'w', encoding="utf-8") as f:
    8     for paragraph in document.paragraphs:
    9         f.write(paragraph.text if paragraph.text else "
    ")

    以上读取段落并另存为txt文本

  • 相关阅读:
    AM8 自定义表情包的实现方法
    Create STKNetDiskC Instance Error
    怎样实现文件发文功能
    企业云盘的数据备份
    一种可行的文档协同编辑方法实现
    【OI】二分图最大匹配
    【OI】位运算操作
    【OI】关于快速幂的简单理解
    【OI】线性筛
    【OI】指针线段树&指针
  • 原文地址:https://www.cnblogs.com/sigai/p/7998263.html
Copyright © 2011-2022 走看看