Asp.net export Excel (datatable export Excel)

Source: Internet
Author: User

This method does not use redundant Excel databases, which is concise.
In addition, you can control the output format, such as changing the header. Record it.

///   <Summary>
/// Export EXCEL from datatable
///   </Summary>
///   <Param name = "DT"> </param>
///   <Param name = "FILENAME"> </param>
Private   Void Createexcel (datatable DT, String Filename)
{
Httpresponse resp;
Resp = Page. response;
Resp. contentencoding = System. Text. encoding. getencoding ( " Gb2312 " );
Resp. appendheader ( " Content-Disposition " , " Attachment; filename = "   + Filename );
String Colheaders =   "" , Ls_item =   "" ;

/// /Define table objects and row objects, and use dataset to initialize their values.
// Datatable dt = Ds. Tables [0];
Datarow [] myrow = DT. Select (); // Data filtering can be achieved in the form of DT. Select ("ID> 10 ").
Int I =   0 ;
Int Cl = DT. Columns. count;

// Obtain the titles of each column in the data table. The headers are separated by T. A carriage return is followed by the last column title.
For (I =   0 ; I < Cl; I ++ )
{
If (I = (CL -   1 )) // Add n to the last column.
{
Colheaders + = DT. Columns [I]. Caption. tostring () +   " \ N " ;
}
Else
{
Colheaders + = DT. Columns [I]. Caption. tostring () +   " \ T " ;
}

}
Resp. Write (colheaders );
//Write the obtained data to the HTTP output stream

// Process Data row by row
Foreach (Datarow row In Myrow)
{
// The data in the current row is written to the HTTP output stream, and ls_item is left blank for downstream data
For (I =   0 ; I < Cl; I ++ )
{
If (I = (CL -   1 )) // Add n to the last column.
{
Ls_item + = Row [I]. tostring () +   " \ N " ;
}
Else
{
Ls_item + = Row [I]. tostring () +   " \ T " ;
}

}< br> resp. write (ls_item);
ls_item = " " ;

}
Resp. End ();
}
Protected VoidBtnout_click (ObjectSender, eventargs E)
{
Datatable dt=Dbutility. oledbhelper. executedt ("Select * From t_customer");
Createexcel (DT,"Hello.xls");
}

 

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.