using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
namespace RunExcel
{
class Program
{
static void Main(string[] args)
{
Application excel = null;
_Workbook wrkBook = null;
dynamic sheet = null;
try
{
excel = new Application();
wrkBook = excel.Workbooks.Add();
sheet = wrkBook.Sheets.Add();
sheet.Cells(1, 1).Value = "ABC";
wrkBook.SaveAs(@"d:\PathNotThere\" + Guid.NewGuid() + ".xlsx");
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
}
finally
{
//注意: Excel是Unmanaged程式,要妥善結束才能乾淨不留痕跡
//否則,很容易留下一堆excel.exe在記憶體中
//所有用過的COM+物件都要使用Marshal.FinalReleaseComObject清掉
//COM+物件的Reference Counter,以利結束物件回收記憶體
if (sheet != null)
{
Marshal.FinalReleaseComObject(sheet);
}
if (wrkBook != null)
{
wrkBook.Close(false); //忽略尚未存檔內容,避免跳出提示卡住
Marshal.FinalReleaseComObject(wrkBook);
}
if (excel != null)
{
excel.Workbooks.Close();
excel.Quit();
Marshal.FinalReleaseComObject(excel);
}
}
Console.WriteLine("Done");
}
}
}