在.NET4中如果我们将COM的Embed Interop Types属性设置为True,那么COM方法的返回值将自动映射为Dynamic,从而简化COM方法调用。 下面我们通过一个Console Application 导出数据到EXCEL来演示:
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 { get; set; }
public string Company { get; set; }
public string Department { get; set; }
}
}
}
}
}