【程式筆記】使用 Flask 和 Python 自動化 Word 分割工具
2025-10-22 15:32:36

最近被一份超長的 Word 報告綁住了手腳,就順手把常做的流程包成一個小工具:在本機用 Python + Flask 開個頁面,上傳一個 docx 再丟一份純文字的檔名清單,按一下就把每個 Section 拆成各自的新檔。因為用到 pywin32 操作 Word,本工具只在 Windows 上跑(機器要有安裝 Word)。

整體很直覺:進頁面,上傳 docx 和清單,送出。後端把每個 Section 複製到新的文件,順手把頁腳重設或清掉,輸出到指定資料夾。沒有花俏功能,就是把重複工作變成一鍵而已。

核心拆檔的函式大概長這樣:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def split_by_section_with_names(input_doc_path, output_dir, filenames):
pythoncom.CoInitialize()
try:
word_app = win32.Dispatch("Word.Application")
word_app.Visible = False
doc = word_app.Documents.Open(input_doc_path)
total_sections = doc.Sections.Count
if len(filenames) + 1 < total_sections:
doc.Close(False)
word_app.Quit()
return f"Error: Insufficient filenames provided. Expected at least {total_sections - 1}, got {len(filenames)}."
for i in range(1, total_sections):
new_doc = word_app.Documents.Add()
doc.Sections(i).Range.Copy()
new_doc.Range().Paste()
for sec_idx in range(1, new_doc.Sections.Count + 1):
remove_and_set_footer(new_doc.Sections(sec_idx))
new_doc.SaveAs2(os.path.join(output_dir, f"{filenames[i - 1]}.docx"), FileFormat=WD_FORMAT_XML_DOCUMENT)
new_doc.Close(False)
doc.Close(False)
word_app.Quit()
return "Split completed successfully."
finally:
pythoncom.CoUninitialize()

Flask 只做一件事:接到上傳就存到暫存夾、讀檔名清單、呼叫上面那個函式,然後清掉暫存、丟訊息回前端。路由大概是:

1
2
3
4
5
6
7
8
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
doc_file = request.files['doc_file']
filename_file = request.files['filename_file']
# ... 存檔、載入清單、呼叫 split_by_section_with_names()
return redirect(url_for('index'))
return render_template('index.html')

前端就一個表單,兩個檔案欄位加一顆按鈕,Bootstrap 帶過去就好,不特別寫了。

環境方面其實沒什麼:pip install flask pywin32,確定 Windows 上有裝 Word,啟動就 python app.py。打開瀏覽器進 http://127.0.0.1:5000,上傳一組大檔和名稱清單,等個幾秒就會看到輸出檔散落在輸出資料夾裡。

大概就這樣。寫下來主要是給自己備忘:需要把公文照分節拆開時,不用再一份份另存。要改頁腳或輸出命名的細節,就去動 remove_and_set_footer() 或檔名生成那段就行,其他保持極簡。

上一頁
2025-10-22 15:32:36
下一頁