Export a table from a database to an Excel table, "Let clients download Excel"

Source: Internet
Author: User
Tags urlencode

The original Published time: 2008-10-11--from my Baidu article [imported by moving tools]

This example is exported from the GridView to Excel, can be extrapolate, can be directly from the database to be placed in the dataset, and then exported from the DataSet to Excel, the principle is the same ....

Example:

All content in the site folder:

Content in Excel: [with fixed Excel header]

Background code:

Using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;

Using System.IO;
Using System.Data.OleDb;

public partial class _default:system.web.ui.page
{
protected void Page_Load (object sender, EventArgs e)
{

}
protected void Button1_Click (object sender, EventArgs e)
{
String newfilename = DateTime.Now.ToString ("YYYYMMDDHHMMSS") + ". xls";
NewFileName = Server.MapPath (NewFileName);
Formally generate the Excel file according to the template
File.Copy (Server.MapPath ("~/module01.xls"), newfilename,true);
Establish a database connection to the Excel file
String strconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + NewFileName + "; Extended properties= ' Excel 8.0; ';
OleDbConnection Conn = new OleDbConnection (strconn);
Conn.Open ();
OleDbCommand CMD = new OleDbCommand ("", Conn);
foreach (GridViewRow gr in gridview1.rows)
{
String sql = "INSERT INTO [sheet1$]";
SQL + = "([Course number],[course name]) VALUES (";
SQL + = "'" + gr. Cells[0]. Text + "', '" + gr. CELLS[1]. Text + "')";
Cmd.commandtext = SQL;
Cmd.executenonquery ();
}
Conn.close ();
Open the file you want to download and store it in FileStream
FileStream fs = File.openread (NewFileName);
bytes remaining in file transfer: The initial value is the total size of the file
Long length = fs. Length;

Response.Buffer = false;
Response.AddHeader ("Connection", "keep-alive");
Response.ContentType = "Application/octet-stream";
Response.AddHeader ("Content-disposition", "attachment;filename=" + Server.URLEncode ("course. xls"));
Response.AddHeader ("Content-length", Length. ToString ());

storing buffers to send data
byte[] buf = new byte[1000];

Number of bytes per actual read
int bytetoread;
The remaining bytes are nonzero and continue to be transmitted
while (length > 0)
{
Client browser is still open, continue to transfer
if (response.isclientconnected)
{
Read data into buffer
Bytetoread = fs. Read (buf, 0, 1000);
Writes buffer data to the client browser
Response.OutputStream.Write (buf, 0, Bytetoread);
Write to client now
Response.Flush ();
Reduced number of bytes left
Length-= Bytetoread;
}
Else
{
The client browser has been disconnected, preventing the loop from continuing
length =-1;
}
}
Fs. Close ();
File.delete (NewFileName);
}
}

The second method:

protected void button2_click (object sender, EventArgs e)
{
Response.Clear ();
Response.Buffer = true;
Response.AddHeader ("Content-disposition", "attachment;filename=" + Server.URLEncode ("course. xls")); Define output file and file name
response.contentencoding = System.Text.Encoding.GetEncoding ("GB2312");//Set output stream to Simplified Chinese
Response.ContentType = "Excel";//Set Output file type to excel file.
This. EnableViewState =false;
System.Globalization.CultureInfo Mycitrad = new System.Globalization.CultureInfo ("ZH-CN", true);
StringWriter ostringwriter = new StringWriter (Mycitrad);
HtmlTextWriter ohtmltextwriter = new HtmlTextWriter (Ostringwriter);
This. Gridview1.rendercontrol (Ohtmltextwriter); The DataGrid to export
Response.Write (Ostringwriter.tostring ());
Response.End ();
}
The above method will also overload this method in this page, otherwise the following exception
The control "GridView1" of type "GridView" must be placed inside a form tag with Runat=server.
public override void Verifyrenderinginserverform (Control control)
{
}

Export a table from a database to an Excel table, "Let clients download 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.