ASP. NET export EXCEL from List

Source: Internet
Author: User

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 ();
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.