You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发Plotly Dash应用:如何创建只读MS Word文档?

Python 创建只读MS Word文档的解决方案

一、python-docx 间接实现只读

python-docx的API确实没有直接设置文档只读的选项,但可以通过两种间接方式实现:

  • 设置文件系统只读属性:生成文档后,调用系统API修改文件属性。以Windows为例:
import win32api
import win32con

# 生成docx文档后执行
file_path = "target.docx"
win32api.SetFileAttributes(file_path, win32con.FILE_ATTRIBUTE_READONLY)

Linux/macOS则用os.chmod:

import os

os.chmod("target.docx", 0o444)  # 只读权限
  • 转换为PDF(更可靠的只读方式):如果用户接受PDF格式,用docx2pdf库将生成的docx转为PDF,天然具备只读特性:
from docx2pdf import convert
convert("target.docx")

二、Plotly Dash 技术栈适配方案

1. 后端生成+只读处理+前端下载

在Dash中通过后端生成docx,设置只读属性后,用dcc.Download组件提供下载:

import dash
from dash import dcc, html, Input, Output
import docx
import win32api
import win32con
import tempfile

app = dash.Dash(__name__)

app.layout = html.Div([
    html.Button("获取只读Word文档", id="trigger-download"),
    dcc.Download(id="docx-download")
])

@app.callback(
    Output("docx-download", "data"),
    Input("trigger-download", "n_clicks"),
    prevent_initial_call=True
)
def generate_and_protect_docx(_):
    # 创建文档内容
    doc = docx.Document()
    doc.add_heading("只读文档示例", level=1)
    doc.add_paragraph("此文档已设置为只读")
    
    # 临时保存并设置只读
    with tempfile.NamedTemporaryFile(suffix=".docx", delete=False) as tmp:
        doc.save(tmp.name)
        win32api.SetFileAttributes(tmp.name, win32con.FILE_ATTRIBUTE_READONLY)
    
    return dcc.send_file(tmp.name, filename="readonly_document.docx")

if __name__ == "__main__":
    app.run_server(debug=True)

2. Redocx 相关说明

Redocx是React端生成Word的库,它本身不支持直接设置文档只读属性。可以在前端生成文档后,提示用户手动设置文件只读,或者将生成的文档数据传给Dash后端,由后端处理为只读文件后再返回下载。

三、进阶保护方案

如果需要更严格的文档保护(比如限制编辑但允许阅读),可以手动创建带有限制编辑保护的Word模板,然后用python-docx-template库填充内容,模板中的保护设置会被保留。

内容的提问来源于stack exchange,提问作者Dee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 18:30:14