Python+spire.doc:读取Word文档内容

目录

读取全部文本内容

通过节点读取数据

按页读取

读取页眉页脚

遍历表格数据

查找指定文本


spire的更多使用和方法可见:

冰蓝科技 e-iceblue | 您的办公文档开发技术专家 | C#/VB.Net Excel, Word, PowerPoint, PDF, Barcode 组件

注意,文件在读取或写入操作时必须是关闭状态,否则会报错。

读取全部文本内容

from spire.doc import *
from spire.doc.common import *

inputFile = r'自检测试报告.doc'
outputFile = r'自检测试报告.docx'

document = Document()  # 创建Document实例
document.LoadFromFile(inputFile)  # 加载Word文档
document_text = document.GetText()
print(document_text)

通过节点读取数据

Document.Sections[index] 属性可用于获取Word 文档中的特定节点。 获取后,可遍历该节中的段落、表格等。

print(len(document.Sections))  # 获取节点数量
print(document.Sections.Count)  # 获取节点数量
section = document.Sections

# 分段落获取文本内容
for i in range(document.Sections.Count):
    paragraphs = section[i].Paragraphs
    for p in range(paragraphs.Count):
        print(paragraphs[p].Text)

按页读取

因为Word文档本质上是流式文档,流式布局,所以没有“页面”的概念。为了方便页面操作,Spire.Doc for Python提供了FixedLayoutDocument类,用于将Word文档转换为固定布局。

layoutDoc = FixedLayoutDocument(document)  # 创建FixedLayoutDocument类的实例,用于将Word文档转换为固定布局。

print(layoutDoc.Pages.Count)

for p in range(layoutDoc.Pages.Count):
    page_data = layoutDoc.Pages[p]
    # print(page_data.Text)   # 按页读取文本
    cols_data = page_data.Columns
    for col in range(len(cols_data)):
        # print(cols_data[col].Text)  # 按段读取文本
        row_data = cols_data[col].Lines
        for row in range(len(row_data)):
            print(row_data[row].Text)  # 按行读取文本

读取页眉页脚

section = document.Sections

for i in range(document.Sections.Count):

    header = section[i].HeadersFooters.Header  # 获取该节的页眉对象

    footer = section[i].HeadersFooters.Footer  # 获取该节的页脚对象
    for h in range(header.Paragraphs.Count):
        headerPara = header.Paragraphs[h]
        print(headerPara.Text)
        
    for f in range(footer.Paragraphs.Count):
        footerPara = footer.Paragraphs[f]
        print(footerPara.Text)

遍历表格数据

document = Document()  # 创建Document实例
document.LoadFromFile(inputFile)  # 加载Word文档

for i in range(document.Sections.Count):
    section = document.Sections.get_Item(i)
    for j in range(section.Tables.Count):
        table = section.Tables.get_Item(j)

        # 遍历表格中的行
        for row in range(table.Rows.Count):
            row_data = []

            # 遍历行中的单元格
            for cell in range(table.Rows.get_Item(row).Cells.Count):
                cell_obj = table.Rows.get_Item(row).Cells.get_Item(cell)
                cell_text = ""

                # 获取单元格中的段落内容
                for paragraph_index in range(cell_obj.Paragraphs.Count):
                    paragraph = cell_obj.Paragraphs.get_Item(paragraph_index)
                    cell_text += paragraph.Text

                row_data.append(cell_text.strip())

            # 打印行数据
            print(row_data)
            
document.Close()

查找指定文本

def FindAllString(self ,matchString:str,caseSensitive:bool,wholeWord:bool)->List['TextSelection']:

参数:

  • matchString:str,要查找的内容
  • caseSensitive:bool,如果为True,匹配是区分大小写的。
  • wholeWord:bool,如果为True,匹配的必须是一个完整的单词。

可对查找的内容进行其他操作

document = Document()  # 创建Document实例
document.LoadFromFile(inputFile)  # 加载Word文档

textSelections = document.FindAllString("测试报告", False, True)

# 对找到的内容设置高亮显示颜色
for selection in textSelections:
    selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.get_Blue()

document.SaveToFile(outputFile, FileFormat.Docx)
document.Close()
### 使用 Spire.Doc 进行 Python 文档操作 为了在 Python 中使用 Spire.Doc 处理 Word 文档,首先需要安装适用于 PythonSpire.Doc 库。可以通过 pip 安装此库: ```bash pip install spire.doc ``` #### 创建和编辑文档 下面是一个简单的例子,展示如何创建一个新的 Word 文档并向其中添加一些内容。 ```python from spire.doc import Document, ParagraphStyle # 初始化新文档对象 document = Document() # 向文档中添加一个段落 paragraph = document.AddSection().AddParagraph() paragraph.AppendText("这是一个测试段落") # 设置段落样式 style = ParagraphStyle(document) style.Font.Name = "Arial" style.Font.Size = 12 paragraph.ApplyStyle(style) # 将文档保存至指定路径 document.SaveToFile("example_output.docx", FileFormat.DocX) print("Document created successfully.") ``` 这段代码展示了基本的操作流程:初始化 `Document` 对象、添加文本以及设置字体属性,并最终将结果保存为 `.docx` 文件[^1]。 对于更复杂的任务,比如读取现有文件并修改其内容,则可以按照如下方式加载已有文档: ```python from spire.doc import Document # 加载现有的Word文档 existing_doc = Document() existing_doc.LoadFromFile("input_file.docx") # 修改第一个段落的内容 if existing_doc.Sections.Count > 0 and \ existing_doc.Sections[0].Body.Paragraphs.Count > 0: first_paragraph = existing_doc.Sections[0].Body.Paragraphs[0] first_paragraph.Text = "已更新的首段文字" # 另存为新的文件名 existing_doc.SaveToFile("modified_document.docx", FileFormat.DocX) print("Existing document modified and saved as new file.") ``` 通过这种方式可以在不改变原文件的情况下完成对文档内容的各种更改[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值