C# 将具有随机行和列(由对象定义)的表导出到excel
我有一项任务,我确信可以用一种简单的方式简单地概括 我有不同的表要动态导出到excel,我所做的是从对象参数以HTML格式创建表列,并使用列表上的foreach创建行 例如,如果我有一个客户列表(C# 将具有随机行和列(由对象定义)的表导出到excel,c#,asp.net,.net,reflection,parameters,C#,Asp.net,.net,Reflection,Parameters,我有一项任务,我确信可以用一种简单的方式简单地概括 我有不同的表要动态导出到excel,我所做的是从对象参数以HTML格式创建表列,并使用列表上的foreach创建行 例如,如果我有一个客户列表(list) 我根据对象属性的数量和名称创建tr: public class Customer { public int DeliveryAddressId { get; set; } public DateTime CreatedDate { get; set; } public
list
)
我根据对象属性的数量和名称创建tr:
public class Customer
{
public int DeliveryAddressId { get; set; }
public DateTime CreatedDate { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
....
}
var output = "<table>";
output += "<thead>";
output += "<tr>";
output += "<th>DeliveryAddressId </th>";
.....
公共类客户
{
public int DeliveryAddressId{get;set;}
公共日期时间CreatedDate{get;set;}
公共字符串名{get;set;}
公共字符串Lastname{get;set;}
....
}
var输出=”;
输出+=“”;
输出+=“”;
输出+=“DeliveryAddressId”;
.....
和用于填充行的foreach:
foreach (var customer in List<Customer>)
{
output += "<tr>";
output += "<td>" + customer.DeliveryAddressId + "</td>";
.....
foreach(列表中的var客户)
{
输出+=“”;
输出+=“”+customer.DeliveryAddressId+“”;
.....
但是我有不同的对象和不同的参数,所以问题是:
如何创建一个以
列表
为输入的通用方法,并使用对象参数名称作为列名称创建此类表,然后相应地循环行?如果创建一个接受T
列表的通用方法
public string DumpToTable<T>(List<T> list) {
}
根据您的使用情况,您可能希望使用.GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly);
来筛选继承的成员
对于每个PropertyInfo
元素,您可以在生成标题时访问它们的.Name
之后,在列表中迭代,您必须调用它们的相对.GetValue
方法:
foreach(T item in list) {
string line = "";
foreach(PropertyInfo prop in props) {
line += string.Format("<td>{0}</td>", prop.GetValue(item));
}
output += string.Format("<tr>{0}</tr>", line);
}
foreach(列表中的T项){
字符串行=”;
foreach(PropertyInfo props in props){
line+=string.Format(“{0}”,prop.GetValue(item));
}
输出+=string.Format(“{0}”,第行);
}
如果您创建一个接受T
public string DumpToTable<T>(List<T> list) {
}
根据您的使用情况,您可能希望使用.GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly);
来筛选继承的成员
对于每个PropertyInfo
元素,您可以在生成标题时访问它们的.Name
之后,在列表中迭代,您必须调用它们的相对.GetValue
方法:
foreach(T item in list) {
string line = "";
foreach(PropertyInfo prop in props) {
line += string.Format("<td>{0}</td>", prop.GetValue(item));
}
output += string.Format("<tr>{0}</tr>", line);
}
foreach(列表中的T项){
字符串行=”;
foreach(PropertyInfo props in props){
line+=string.Format(“{0}”,prop.GetValue(item));
}
输出+=string.Format(“{0}”,第行);
}
我想要的甜味。谢谢我想要的甜味。谢谢