如何替换docx文件指定的内容?并返回文件流?

如何替换docx文件指定的内容?并返回文件流?

如何替换docx文件指定的内容?并返回文件流?

阅读 592
2 个回答

用python代码作答。

import io
from docx import Document


def replace_text_in_docx(docx_stream, old_text, new_text):
    try:
        # 从文件流创建 Document 对象
        doc = Document(docx_stream)
        # 遍历文档中的段落
        for paragraph in doc.paragraphs:
            if old_text in paragraph.text:
                # 替换段落中的文本
                paragraph.text = paragraph.text.replace(old_text, new_text)
        # 遍历文档中的表格
        for table in doc.tables:
            for row in table.rows:
                for cell in row.cells:
                    for paragraph in cell.paragraphs:
                        if old_text in paragraph.text:
                            # 替换表格单元格中的文本
                            paragraph.text = paragraph.text.replace(old_text, new_text)

        # 创建一个内存中的文件流
        output_stream = io.BytesIO()
        # 将修改后的文档保存到文件流中
        doc.save(output_stream)
        # 将文件流指针重置到开头
        output_stream.seek(0)
        return output_stream
    except Exception as e:
        print(f"发生错误: {e}")
        return None


# 示例用法
if __name__ == "__main__":
    # 打开文件并以二进制模式读取
    with open('123.docx', 'rb') as file:
        docx_stream = file.read()
    old_text = "旧文本"
    new_text = "新文本"
    output_stream = replace_text_in_docx(io.BytesIO(docx_stream), old_text, new_text)
    if output_stream:
        # 可以将输出流保存到文件
        with open('output.docx', 'wb') as output_file:
            output_file.write(output_stream.read())
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题