想要在C#程式中讓Excel寫入資料,就只要在在程式中間加入下列語法就可以了
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程式
mySheet.Cells.Font.Name = "標楷體"; //設定Excel資料字體字型
mySheet.Cells.Font.Size = 20; //設定Excel資料字體大小
//Excel寫入資料
mySheet.Cells[1, 1] = "1";
mySheet.Cells[1, 2] = "A";
mySheet.Cells[2, 1] = "2";
mySheet.Cells[2, 2] = "B";
mySheet.Cells[3, 1] = "3";
mySheet.Cells[3, 2] = "C";
mySheet.Cells[4, 1] = "4";
mySheet.Cells[4, 2] = "D";
}
catch (Exception)
{
myExcel.Visible = true;
}
finally
{
//把執行的Excel資源釋放
System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);
myExcel = null;
myBook = null;
mySheet = null;
}
}
Excel畫面結果

文章標籤
全站熱搜
