if (xlApp == null) { Console.WriteLine("Error! xlApp"); return; } //用Excel应用程式建立一个Excel物件,也就是Workbook。并取得Workbook中的第一个sheet。这就是我们要操作资料的地方。 wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet); ws = (Worksheet)wb.Worksheets[1]; if (ws == null) { Console.WriteLine("Error! ws"); } //要在Excel储存资料,有三种方式,以下分别介绍。利用Range物件,设定要储存资料的储存格范围。 // Select the Excel cells, in the range c1 to c7 in the worksheet. Range aRange = ws.get_Range("C1", "C7"); if (aRange == null) { Console.WriteLine("Could not get a range. Check to be sure you have the correct versions of the office DLLs."); } // Fill the cells in the C1 to C7 range of the worksheet with the number 6. Object[] args = new Object[1]; args[0] = 6; aRange.Value2 = args; //衍生自上面方法,但是在储存资料的时候,可以用InvokeMember呼叫aRange的资料成员(成员函式?)。 //aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args); //利用Cells属性,取得单一储存格,并进行操作。 string[] number = { "A", "B", "C", "D", "E" }; foreach (string s in number) { Range aRange2 = (Range)ws.Cells["1", s]; Object[] args2 = new Object[1]; args2[0] = s; aRange2.Value2 = args2; }