步驟一

C#要在程式內開啟Excel試算表,必須先安裝Office軟體,然後再加入參考。

加入參考要選擇 Microsoft  Excel14.0 Object  Library  這個參考檔案,如下圖所示↓

 

步驟二

加入參考之後,還要在上面宣告Excel物件。

using Excel = Microsoft.Office.Interop.Excel; ←輸入這段語法

 

步驟三

我在程式介面放上一個按鈕(button1),用來開啟Excel。

 

步驟四

我在 button1 輸入以下程式碼。

private void button1_Click(object sender, EventArgs e)
{
Excel._Application myExcel = null;
Excel._Workbook myBook = null;
Excel._Worksheet mySheet = null;

try
{
myExcel = new Excel.Application();    //開啟一個新的應用程式
myExcel.DisplayAlerts = false;        //停用警告訊息
myBook = myExcel.Workbooks.Add(true); //新增活頁簿
mySheet = (Excel._Worksheet)myBook.Worksheets[1];//引用第一張工作表
myExcel.Visible = true;               //顯示Excel程式
}
catch (Exception)
{
myExcel.Visible = true;
}
finally
{
//把執行的Excel資源釋放
System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);
myExcel = null;
myBook = null;
mySheet = null;
}
}

 

這就是開啟Excel的基本語法,只要Key入上面語法,就能成功開啟Excel。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

文章標籤
全站熱搜
創作者介紹
創作者 熊仔 的頭像
熊仔

熊仔的部落格

熊仔 發表在 痞客邦 留言(0) 人氣(3,866)