在c#如何:使用 COM Interop 建立 Excel 電子表格

wisdomone1發表於2011-08-18


從上述連結摘選關於application,workbook,worksheet,range的cs程式碼


using System;
using System.Reflection; 
using Microsoft.Office.Interop.Excel;

public class CreateExcelWorksheet
{
    static void Main()
    {
//excel應用程式
 Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) { Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct."); return; }
//excel應用程式可用
xlApp.Visible = true; //在excel應用程式中新增workbook(工作薄) Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
//同理,在workbook新增worksheets,相當於excel一個頁籤
Worksheet ws = (Worksheet)wb.Worksheets[1]; if (ws == null) { Console.WriteLine("Worksheet could not be created. Check that your office installation and project references are correct."); } // 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;

//反射gettype()
 aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args); // Change the cells in the C1 to C7 range of the worksheet to the number 8. aRange.Value2 = 8; } }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/9240380/viewspace-705295/,如需轉載,請註明出處,否則將追究法律責任。

相關文章