在 C# 裡開啟 Word 檔其實難度不高,可用的做法也有好幾種。本文整理兩條常見路線:一條走 WinForm 加 COM 組件,一條走瀏覽器端的 ActiveX。
首先在專案引用中加入 Microsoft Word 11.0 Object Library,接著用 OpenFileDialog 讓使用者挑選要開啟的檔案(.doc、.txt、.rtf 都支援),再把內容抓進 RichTextBox 顯示。
private void button1_Click(object sender, System.EventArgs e)
{
// 挑選要開啟的 Word/RTF/文字檔
OpenFileDialog opd = new OpenFileDialog();
opd.InitialDirectory = "c:\\";
opd.Filter = "Word文檔(*.doc)|*.doc|文本文檔(*.txt)|*.txt|RTF文檔(*.rtf)|*.rtf|所有文檔(*.*)|*.*";
opd.FilterIndex = 1;
if (opd.ShowDialog() == DialogResult.OK && opd.FileName.Length > 0)
{
// 建立 Word 應用程式實例
// 缺點:表格、圖片等無法正確呈現
Word.ApplicationClass app = new Word.ApplicationClass();
Word.Document doc = null;
object missing = System.Reflection.Missing.Value;
object FileName = opd.FileName;
object readOnly = false;
object isVisible = true;
try
{
doc = app.Documents.Open(ref FileName, ref missing, ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref isVisible, ref missing,
ref missing, ref missing, ref missing);
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
// 從剪貼簿取回純文字
IDataObject data = Clipboard.GetDataObject();
this.richTextBox1.Text = data.GetData(DataFormats.Text).ToString();
}
finally
{
if (doc != null)
{
doc.Close(ref missing, ref missing, ref missing);
doc = null;
}
if (app != null)
{
app.Quit(ref missing, ref missing, ref missing);
app = null;
}
}
}
}
這段寫法要注意兩點:一是 COM 互動必須放在 try/finally 中收尾,否則 Word 進程容易殘留在背景;二是靠剪貼簿取文字只能拿到純文字,表格與圖片會全部流失。
先把頁面骨架搭好:一個檔案選擇控制項加一顆按鈕。
<input id="flUpload" type="file" />flUpload
<input id="btnOpenFile" type="button" value="button" onclick="OpenFile()" />
再寫 OpenFile 方法,依副檔名決定要啟動 Excel 還是 Word:
function OpenFile()
{
if (document.getElementById("flUpload").value.toUpperCase().indexOf(".XLS") != -1)
{
var objExcel;
objExcel = new ActiveXObject("Excel.Application");
objExcel.Visible = true;
objExcel.Workbooks.Open(document.getElementById("flUpload").value);
}
else if (document.getElementById("flUpload").value.toUpperCase().indexOf(".DOC") != -1)
{
var objDoc;
objDoc = new ActiveXObject("Word.Application");
objDoc.Visible = true;
objDoc.Documents.Open(document.getElementById("flUpload").value);
}
else
{
alert("Please select Word/Excel file only");
return false;
}
}
完成後在 IE 中先選好 doc 檔,按下 open 就能開啟。
這套寫法完全依賴 ActiveXObject,因此只在 Internet Explorer 且本機安裝了 Office 的環境下有效,同時必須把網站加入信任區域、允許執行 ActiveX 控制項。現代瀏覽器基於安全模型早已移除這項能力,若要在新環境實作同樣的功能,應該改走 File API 搭配伺服器端解析(例如以 OpenXML 讀取 .docx),而不是繼續沿用 ActiveX 方案。