C#中建立、打開、讀取、寫入、保存Excel的通常性代碼

首先,在引用的COM中找到Microsoft Excel 11.0 Object Library,添加。

using System;
using System.Reflection; // 引用這個才能使用Missing字段  using Excel;
namespace CExcel1
{
    class Class1
    {
        [STAThread]   static void Main(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;
    }
}
相關文章
相關標籤/搜索