上一篇我們學會了如何用 API 開啟一個空白的 Word 文件。
但 AI 助手的價值在於能「幫我們做事」,所以這一篇,我們要讓 AI 自動幫我們把文字寫入 Word 文件。
這個 API 可以:
class WordRequest(BaseModel):
content: str = "這是預設的文字。"
@app.post("/open-word")
def open_word_and_type(request: WordRequest):
"""
開啟 Word 應用程式並將指定的文字寫入。
"""
print(f"[DEBUG] 收到 open-word 請求: {request.content}")
logger.info(f"收到 open-word 請求,內容: {request.content}")
word_app = None
try:
# 在多執行緒環境中,必須先初始化 COM
pythoncom.CoInitialize()
# 嘗試取得現有的Word實例,如果沒有則創建新的
try:
word_app = win32.GetObject(Class="Word.Application")
if word_app.Documents.Count == 0:
# 沒有開啟的文件,創建新文件
doc = word_app.Documents.Add()
else:
# 有開啟的文件,使用第一個活動文件
doc = word_app.ActiveDocument
# 清空現有內容
doc.Range().Text = ""
except:
# 如果取得現有實例失敗,創建新的Word應用程式
word_app = win32.Dispatch("Word.Application")
word_app.Visible = True
doc = word_app.Documents.Add()
# 確保Word是可見的
word_app.Visible = True
# 寫入內容
content = request.content if request.content.strip() else "這是一個新的Word文件。"
# 使用更安全的方式寫入內容
try:
# 方法1:使用Range
doc.Range().Text = content
except:
try:
# 方法2:使用Selection
word_app.Selection.TypeText(content)
except:
# 方法3:使用Paragraphs
doc.Paragraphs(1).Range.Text = content
logger.info("已成功開啟 Word 並寫入內容。")
return {"status": "success", "message": f"已開啟 Word 並寫入:'{content}'"}
except Exception as e:
error_msg = str(e)
logger.error(f"開啟 Word 時發生錯誤: {error_msg}")
if "(-2147352567" in error_msg:
return {"status": "error", "message": "Word 啟動失敗。請確保 Microsoft Word 已正確安裝。"}
else:
return {"status": "error", "message": f"開啟 Word 時發生錯誤: {error_msg}"}
finally:
try:
pythoncom.CoUninitialize()
except:
pass
逐行拆解:
逐行拆解:
資料模型定義class WordRequest(BaseModel)
- 使用 Pydantic 定義請求格式,包含預設值
函數定義def open_word_and_type(request: WordRequest):
- 注意不是 async 函數
COM 環境初始化pythoncom.CoInitialize()
- 多執行緒環境下操作 COM 物件的必要步驟
智能檢查現有實例
內容處理
安全清理finally
區塊確保 COM 環境正確清理
使用者發送請求:
POST http://127.0.0.1:8000/open-word
Content-Type: application/json
{
"content": "Hello, this is AI writing into Word!"
}
API 智能處理:
成功時:
{
"status": "success",
"message": "已開啟 Word 並寫入:'Hello, this is AI writing into Word!'"
}
失敗時:
{
"status": "error",
"message": "Word 啟動失敗。請確保 Microsoft Word 已正確安裝。"
}