.NET4进行COM互操作导出数据到Excel

在.NET4之前COM互操作会面临2大困扰:

1).可选参数,我们需要为每一个可选参数指定Type.Missing值

2).COM方法的返回值都是特殊的数据类型我们在操作的时候必须进行类型转换

在.NET4中如果我们将COM的Embed Interop Types属性设置为True,那么COM方法的返回值将自动映射为Dynamic,从而简化COM方法调用。 下面我们通过一个Console Application 导出数据到EXCEL来演示:

1.构建一个Console Application命名为COMInterop.Demo

2.添加COM References:Microsoft.Office.Interop.Excel (设置Embed Interop Types属性为True)

3.代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;

namespace COMInterop.Demo
{
    class Program
    {
        static IList<Person> persons;
        static void Main(string[] args)
        {
            InitializeData();
            ExportDataToExcel();
        }
        private static void ExportDataToExcel()
        {
            if (persons == null || persons.Count == 0)
            {
                throw new Exception("导出数据为空或者无数据!");
            }
            Excel.Application app = new Excel.Application();
            app.Workbooks.Add();
            Excel.Worksheet sheet = app.ActiveSheet;
            sheet.Cells[1"A"] = "EmployeeName";
            sheet.Cells[1"B"] = "Company";
            sheet.Cells[1"C"] = "Department";
            int rowIndex = 1;
            foreach (var item in persons)
            {
                rowIndex++;
                sheet.Cells[rowIndex, "A"] = item.Name;
                sheet.Cells[rowIndex, "B"] = item.Company;
                sheet.Cells[rowIndex, "C"] = item.Department;
            }
            sheet.Range["A1"].AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormat3DEffects1);
            sheet.SaveAs(Path.Combine(Environment.CurrentDirectory, "EmployeeInformation.xlsx"));
            app.Quit();
            Console.ReadKey();
        }

        private static void InitializeData()
        {
            persons = new List<Person>
            { 
            new Person{ Name="Fiona", Company="CPI", Department="Software"},
            new Person{ Name="Tony", Company="Baidu", Department="MIS"},
            new Person{ Name="Grady", Company="Google", Department="Marketing"}
            };
        }
        public class Person
        {
            public string Name { getset; }
            public string Company { getset; }
            public string Department { getset; }
        }
    }

  } 

 } 


原文地址:https://www.cnblogs.com/jeriffe/p/2242147.html