How to export GridView Excel?

xiaoxiao2021-04-07  374

First, define document type, character encoding

Response.clear ();

Response.buffer = true;

Response.Charset = "UTF-8";

// This is very important, the attachment parameter represents the download as an attachment, you can change it to ONLINE

//filename=FileFlow.xls Specifies the name of the output file, pay attention to its extension and specified file type, can be: .doc || .xls ||.txt || .htm

Response.Appendheader ("Content-Disposition", "Attachment; FileName = fileflow.xls");

Response.contentencoding = system.text.Encoding.Getencoding ("UTF-8");

//Response.contentType Specify file types can be Application / MS-Excel || Application / MS-Word || Application / MS-TXT || Application / MS-HTML || or other browser to support documentation directly

Response.contentType = "Application / MS-Excel";

THIS.ENABLEVIEWSTATE = false;

Second, define an input stream

System.io.stringwriter ostringwriter = new system.io.stringwriter ();

System.Web.ui.htmlTextWriter OhtmlTextWriter = new system.web.ui.htmlTextWriter;

Third, bind the target data to the input stream output

THIS.RenderControl (OhtmlTextWriter);

// this represents the output page, you can also bind DataGrid, or other controls that support Obj.RenderControl () properties

Response.write (ostringwriter.tostring ());

Response.end ();

Summary: This routine is tested under the Microsoft Visual Studio .Net 2003 platform, for C # and VB, change the THIS keyword to ME when using VB.

A simplified way:

Response.clear ()

Response.buffer = TRUE

Response.charset = "GB2312"

Response.Appendheader ("Content-Disposition", "Attachment; FileName =" System.Datetime.today.toshortdateString () ".xls")

Response.contentencoding = system.text.Encoding.getencoding ("GB2312")

Response.contentType = "Application / MS-Excel"

ME.enableViewState = false

Dim Mycitrad AS New System.globalization.cultureInfo ("ZH-CN", TRUE)

Dim OstringWriter as new system.io.stringWriter (MyCITRAD)

Dim ohtmltextwriter as new system.web.ui.htmlTextWriter (OstringWriter) GridView1.RenderControl (OhtmlTextWriter)

Response.write (ostringwriter.tostring ())

Response.end ()

转载请注明原文地址:https://www.9cbs.com/read-132440.html

New Post(0)