如何替换docx文件指定的内容?并返回文件流?
如何替换docx文件指定的内容?并返回文件流?
用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())
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答5.2k 阅读✓ 已解决
1 回答3.3k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
https://docx.js.org/api/