透過 ActiveXObject 直接引用 Microsoft 的 COM 元件,可以在網頁中生成 Word 文件。本文示範實作的 JavaScript 程式碼(僅適用於支援 ActiveX 的 Internet Explorer 環境)。
<SCRIPT LANGUAGE="text/javascript">
function word_onclick(){
var myDocApp=null;
myDocApp =new ActiveXObject("word.Application");
myDocApp.Application.Visible = true;
var myDoc = myDocApp.Documents.Add();
myDocApp.Selection.ParagraphFormat.Alignment=1;
myDocApp.Selection.Range.Bold=true;
myDocApp.Selection.Font.Size=22;
myDocApp.Selection.Text="請假申請單";
myDocApp.Selection.insertAfter("\n");
myDocApp.Selection.MoveRight(2,10);
myDocApp.Selection.TypeParagraph();
myDocApp.Selection.Font.Bold=false;
myDocApp.Selection.Font.Size=12;
var myTable0=myDoc.Tables.Add(myDocApp.Selection.Range,3,4);
myTable0.cell(1,1).Range.Text="請假人";
myTable0.cell(1,2).Range.Text="張三";
myTable0.cell(1,3).Range.Text="請假時間";
myTable0.cell(1,4).Range.Text="2006-2-10";
myTable0.cell(2,1).Range.Text="工號";
myTable0.cell(2,2).Range.Text="32412";
myTable0.cell(2,3).Range.Text="填表時間";
myTable0.cell(2,4).Range.Text="2006-2-9";
myTable0.cell(3,1).Range.Text="請假原因";
myTable0.cell(3,2).Range.Text="感冒";
myTable0.cell(3,3).Range.Text="處理方式";
myTable0.cell(3,4).Range.Text="病假";
var range=myDocApp.ActiveDocument.Content;
range.Collapse(0);
range.insertAfter("\n");
range=myDocApp.ActiveDocument.Content;
range.Collapse(0);
var myTable2=myDoc.Tables.Add(range,1,2);
myTable2.Columns(1).SetWidth(320,2);
myTable2.cell(1,1).Range.Text="申請人簽名";
myTable2.cell(1,2).Range.Text="申請人的簽名";
try{
myDocApp.ActiveDocument.SaveAs("e:JaveToWord.doc");
}catch(exception){
alert("浏覽器安全設置過高,保存文件到本地失敗");
myDocApp.Documents.close();
myDocApp.Application.quit();
myDocApp=null;
window.close();
}
}
</SCRIPT>
做法是透過 ActiveXObject("word.Application") 建立 Word 應用程式物件,再操作 Selection 設定字型、粗體、對齊,並用 Tables.Add 動態插入表格、填入內容,最後以 SaveAs 存檔。要注意的是,這套做法依賴 IE 的 ActiveX 與較低的安全性設定,且用 try/catch 在存檔失敗時給出提示,屬於特定環境下的舊式方案。