需在資料庫層直接產生 Word 文件(如報表、匯出功能),避免應用層額外開發。利用 OLE Automation 存儲程序操作 Word.Application COM 物件。
IF OBJECT_ID('ExportToWord') IS NOT NULL DROP PROC ExportToWord
GO
CREATE PROCEDURE ExportToWord
@Text VARCHAR(200) = NULL,
@filename VARCHAR(200) = 'c:\ImportToWord.doc'
AS
BEGIN
DECLARE @object INT, @Range INT, @Documents INT, @Document INT, @hr INT, @result_str VARCHAR(255)
IF @Text IS NULL
BEGIN
PRINT 'You should write text'
RETURN
END
SET NOCOUNT ON
-- 建立 Word.Application 物件
EXEC @hr = sp_OACreate 'Word.Application', @object OUT
IF @hr <> 0 BEGIN PRINT 'error create Word.Application'; RETURN END
-- 取得 Documents 集合
EXEC @hr = sp_OAGetProperty @object, 'Documents', @Documents OUT
IF @hr <> 0 BEGIN PRINT 'error create Documents'; RETURN END
-- 新增文件
EXEC @hr = sp_OAMethod @Documents, 'Add', @Document OUT
IF @hr <> 0 BEGIN PRINT 'error with method Add'; RETURN END
-- 取得 Range 物件
EXEC @hr = sp_OAGetProperty @Document, 'Range', @Range OUT
IF @hr <> 0 BEGIN PRINT 'error create Range'; RETURN END
-- 寫入文字
EXEC @hr = sp_OASetProperty @Range, 'Text', @Text
IF @hr <> 0 BEGIN PRINT 'error set Text'; RETURN END
-- 儲存文件
SELECT @result_str = 'SaveAs("' + @filename + '")'
EXEC @hr = sp_OAMethod @Document, @result_str
IF @hr <> 0 BEGIN PRINT 'error with method SaveAs'; RETURN END
-- 關閉文件與銷毀物件
EXEC @hr = sp_OAMethod @Documents, 'Close'
IF @hr <> 0 BEGIN PRINT 'error with method Close'; RETURN END
EXEC @hr = sp_OADestroy @object
IF @hr <> 0 BEGIN PRINT 'error destroy Word.Application'; RETURN END
END
GO
EXEC ExportToWord @Text = '測試匯出內容', @filename = 'c:\Export\Report.doc'
sp_configure 'Ole Automation Procedures', 1; RECONFIGURE;sp_OA* 替代方案或 CLR 整合。所有 sp_OA* 回傳非 0 即失敗,常見:
- 存取被拒絕(權限不足)
- 類別未註冊(Word 未安裝或版本不符)
- 磁碟空間不足