One drawback of this method is that the attribute of entity must correspond to the column name to be output (for example, Chinese characters) before calling this method...
Code
/** // <Summary>
/// Export a group of objects to excel
/// </Summary>
/// <Typeparam name = "T"> type of the object to be exported </typeparam>
/// <Param name = "objlist"> A group of objects </param>
/// <Param name = "FILENAME"> name of the exported file </param>
/// <Param name = "columninfo"> column Name Information </param>
Public void exexcel <t> (list <t> objlist, string filename, Dictionary <string, string> columninfo)
{
If (columninfo. Count = 0) {return ;}
If (objlist. Count = 0) {return ;}
// Generate EXCEL html
String excelstr = "";
Type mytype = objlist [0]. GetType ();
// Obtain the attribute to be displayed from the passed attribute name information based on reflection
List <system. reflection. propertyinfo> mypro = new list <system. reflection. propertyinfo> ();
Foreach (string cname in columninfo. Keys)
{
System. reflection. propertyinfo P = mytype. getproperty (cname );
If (P! = NULL)
{
Mypro. Add (P );
Excelstr + = columninfo [cname] + "\ t ";
}
}
// Ends if no available attributes are found.
If (mypro. Count = 0) {return ;}
Excelstr + = "\ n ";
Foreach (t obj in objlist)
{
Foreach (system. reflection. propertyinfo P in mypro)
{
Excelstr + = P. getvalue (OBJ, null) + "\ t ";
}
Excelstr + = "\ n ";
}
// Output Excel
Httpresponse rs = system. Web. httpcontext. Current. response;
Rs. contentencoding = system. Text. encoding. getencoding ("gb2312 ");
Rs. appendheader ("content-disposition", "attachment; filename =" + filename );
Rs. contenttype = "application/MS-excel ";
Rs. Write (excelstr );
Rs. End ();
}