我正在尝试开发一个可重用的List to excel方法。使用此示例," https://msdn.microsoft.com/en-us/library/dd264733.aspx"
我看到单元格被单独引用,
workSheet.Cells[1, "A"] = "ID Number";
我希望能够动态地从左到右自动填充列名称以及每个单元格。我认为有一种更好的方法,而不是输入" A"," B" ....." A1"等等直接或甚至比将字母表存储到列表中更好的方式进入workSheet.Cells []。
这是我到目前为止所拥有的,
public static void DownloadExcelFile<T>(List<T> list, string fileName)
{
Excel.Application excelApp = new Excel.Application();
// Make the object visible.
excelApp.Visible = true;
excelApp.Workbooks.Add();
Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
//create column headings
foreach (System.ComponentModel.PropertyDescriptor descriptor in System.ComponentModel.TypeDescriptor.GetProperties(list))
{
//how can I reference workSheet.Cells by row, and have the
//column incremented somehow within the loop?
workSheet.Cells[1, "A"] = descriptor.name;
}
}
答案 0 :(得分:1)
您可以使用序号而不是字母代码:
int colIndex = 1;
foreach (System.ComponentModel.PropertyDescriptor descriptor in System.ComponentModel.TypeDescriptor.GetProperties(list))
{
workSheet.Cells[1, colIndex++] = descriptor.Name;
}