using System;
using System.Reflection;
namespace CExcel1
{
class Class1
{
[STAThread]
static voidMain(string[] args)
{
//建立Application對象
Excel.Application xApp=new Excel.ApplicationClass();
xApp.Visible=true;
//得到WorkBook對象, 可以用兩種方式之一: 下面的是開啟已有的檔案
Excel.Workbook xBook=xApp.Workbooks._Open(@"D:/Sample.xls",
Missing.Value,Missing.Value,Missing.Value,Missing.Value
,Missing.Value,Missing.Value,Missing.Value,Missing.Value
,Missing.Value,Missing.Value,Missing.Value,Missing.Value);
//xBook=xApp.Workbooks.Add(Missing.Value);//建立檔案的代碼
//指定要操作的Sheet,兩種方式:
Excel.Worksheet xSheet=(Excel.Worksheet)xBook.Sheets[1];
//Excel.Worksheet xSheet=(Excel.Worksheet)xApp.ActiveSheet;
//讀取資料,通過Range對象
Excel.Range rng1=xSheet.get_Range("A1",Type.Missing);
Console.WriteLine(rng1.Value2);
//讀取,通過Range對象,但使用不同的介面得到Range
Excel.Range rng2=(Excel.Range)xSheet.Cells[3,1];
Console.WriteLine(rng2.Value2);
//寫入資料
Excel.Range rng3=xSheet.get_Range("C6",Missing.Value);
rng3.Value2="Hello";
rng3.Interior.ColorIndex=6; //設定Range的背景色
//儲存方式一:儲存WorkBook
//xBook.SaveAs(@"D:/CData.xls",Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value
// ,Excel.XlSaveAsAccessMode.xlNoChange,Missing.Value,Missing.Value,Missing.Value
//,Missing.Value,Missing.Value);
//儲存方式二:儲存WorkSheet
//xSheet.SaveAs(@"D:/CData2.xls",Missing.Value,Missing.Value,Missing.Value,Missing.Value
//,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);
//儲存方式三
xBook.Save();
xSheet=null;
xBook=null;
xApp.Quit(); //這一句是非常重要的,否則Excel對象不能從記憶體中退出
xApp=null;
}
}
}