在com中引用“ Microsoft Excel 11.0 Object Library”类
//建立Execl对象
Microsoft.Office.Interop.Excel.Application xApp = new Microsoft.Office.Interop.Excel.Application();
xApp.Visible=false;
//有两种打开方式:
object o = Type.Missing;
//1 打开已有的文件
Microsoft.Office.Interop.Excel.Workbook xBook = xApp.Workbooks._Open("D://AAA.xls", o, o, o, o, o, o, o, o, o, o, o, o);
//2 新建文件的代码
//xBook=xApp.Workbooks.Add(o);
//指定要操作的Sheet,两种方式:
object k = xBook.Sheets[1];
Microsoft.Office.Interop.Excel.Worksheet xSheet = (Microsoft.Office.Interop.Excel.Worksheet)k;
//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();
s
xSheet=null;
xBook=null;
xApp.Quit(); //这一句是非常重要的,否则Excel对象不能从内存中退出
xApp=null;