. NET Export Excel

Source: Internet
Author: User
Tags urlencode

        protected voidBtnprint_click (Objectsender, EventArgs e) {DataTable dt= Dbhelpersql.gettable ("Select B.pronumber as product number, b.name as product name, B.kucun as surplus stock, b.price as product price, a.buynum as purchase quantity, (b.price*a.buynum) as total amount From Shopcar as a,product as B where a.proid=b.id and a.userid="+ session["UserID"] +""); if(dt. Rows.Count = =0) {msgbox.show ( This,"no data, export failed"); }            Else            {                //Export ExcelExcelimport (DT,"Shopping Cart"+datetime.now.tostring ("yyyymmddhhmm")); }        }        protected voidExcelimport (DataTable DT,stringexportfilename) {StringWriter SW=getstringwriter (DT); //Current EncodingHttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding ("GB2312"); //encode the file name of the output            stringFileName =Httputility.urlencode (Exportfilename, System.Text.Encoding.UTF8); //file name            stringstr ="attachment;filename="+ FileName +". xls"; //put the file header output, this file header activates the file download boxHttpContext.Current.Response.AppendHeader ("content-disposition", str);//HTTP header FileHttpContext.Current.Response.ContentType ="Application/ms-excel";  This. Page.enableviewstate =false;            Response.Write (SW);        Response.End (); }        PrivateStringWriter getstringwriter (DataTable dt) {StringWriter SW=NewStringWriter (); //Read Column name            foreach(DataColumn DCinchdt. Columns) SW. Write (DC. ColumnName+"\ t"); //Read column values//a re-lineSW. Write (SW.            NewLine); if(dt! =NULL)            {                foreach(DataRow Drinchdt. Rows) { for(inti =0; i < dt. Columns.count; i++) {SW. Write (Dr[i]. ToString ()+"\ t"); } SW. Write (SW.                NewLine); }} SW.            Close (); returnSW; }

Exporting a DataTable

For large amounts of data, export excel in the same way.
The previous blog describes one way to export Excel: Through a DataTable
This blog introduces another way to export Excel-via the DataGrid.

Process for exporting Excel:
Although this time it is exported through the DataGrid, Excel is not exported from the DataGrid control on the interface. Because the requirement in this actual project is to export the query to Excel, the DataGrid control on the interface only shows part of the page, that is, as mentioned in the previous blog, the control implements pagination, so it is not possible to export directly from the interface control.
But the implementation process is just the same, but this time the DataGrid is dynamically generated.

This export process uses the StringWriter class (writes text information to a string), HtmlTextWriter class: Writes markup characters and text to the ASP. NET server control output stream. (namespace: System.Web.UI)
Control.rendercontrol (HtmlTextWriter)--outputs the contents of the server control to the provided HtmlTextWriter object.
The respose then outputs the StringWriter object.

 /// <summary>    ///Export Excel/// </summary>    /// <param name= "DT" ></param>    /// <param name= "Exportfilename" ></param>    protected voidExcelexport (DataTable DT,stringexportfilename) {DataGrid Dgexcel=NewDataGrid (); Dgexcel.datasource=DT;        Dgexcel.databind (); HttpContext.Current.Response.Charset="GB2312"; stringFileName =Httputility.urlencode (Exportfilename, System.Text.Encoding.UTF8); stringStr="attachment;filename="+filename+". xls"; HttpContext. Current. Response. ContentEncoding=System.Text.Encoding.        UTF7; HttpContext.Current.Response. ContentType="Application/ms-excel"; HttpContext. Current. Response. Appendheader ("content-disposition", str); StringWriter SW=NewStringWriter (); HtmlTextWriter Htmtextwriter=NewHtmlTextWriter (SW); Dgexcel.        RenderControl (Htmtextwriter); Response.        Write (SW); Response.    End (); }
/// <summary>    ///Export Excel button/// </summary>    /// <param name= "Sender" ></param>    /// <param name= "E" ></param>    protected voidBtnexport_click (Objectsender, EventArgs e) {DataTable dt=NewSelectclassroommanager ().        Selectclassroombytypebuildno (Ddlclasstype.selectedvalue, Ddlbuildingid.selectedvalue); if(dt. Rows.Count = =0) Response.Write ("<script>alert (' No data, no need to export aha ');</script>"); Else        {                        //Export ExcelExcelexport (DT,"classrooms"); }    }

When you export Excel with the DataGrid, its exported file name is encoded:

String fileName = Httputility.urlencode (Exportfilename, System.Text.Encoding.UTF8);

The current file encoding for its export:

HttpContext. Current. Response. ContentEncoding =system.text.encoding. UTF7;

But the two exported Excel files are different, the content is the same, but its format is different, using the previous blog DataTable to export Excel, is real Excel, and using the DataGrid exported Excel, looks a bit like notepad. or stick to the picture, let's see.

The DataTable exports Excel as follows:

Original Blog Address

http://blog.csdn.net/yuebinghaoyuan/article/details/6703044

. NET Export Excel

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.