Front-end code: ExportExcel1.aspx
<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "ExportExcel1.aspx. cs" Inherits = "ExportExcel1" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml"> <Head runat = "server"> <Title> export data to EXCEL </title> </Head> <Body> <H3> Table Example, constructed programmatically <Form id = "Form1" runat = server> <Asp: Table id = "Table1" GridLines = "Both" HorizontalAlign = "Center" Font-Name = "Verdana" Font-Size = "8pt" CellPadding = 15 CellSpacing = 0 Runat = "server"/> <Asp: Button ID = "Button1" runat = "server" OnClick = "button#click" Text = "export data"/> </Form> </Body> </Html> |
Background code: ExportExcel1.aspx. cs
Using System; Using System. Data; Using System. Configuration; Using System. Collections; 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; Public partial class ExportExcel1: System. Web. UI. Page { Protected void Page_Load (object sender, EventArgs e) { // Generate rows and cells. TableRow r = new TableRow (); TableCell c1 = new TableCell (); C1.ColumnSpan = 2; C1.Text = "test "; C1.HorizontalAlign = HorizontalAlign. Center; R. Cells. Add (c1 ); Table1.Rows. Add (r ); Int numrows = 3; Int numcells = 2; For (int j = 0; j <numrows; j ++) { TableRow r1 = new TableRow (); For (int I = 0; I <numcells; I ++) { TableCell c = new TableCell (); C. Controls. Add (new LiteralControl ("row" + j. ToString () + ", cell" + I. ToString ())); R1.Cells. Add (c ); } Table1.Rows. Add (r1 ); } } Protected void button#click (object sender, EventArgs e) {
DateTime dt = System. DateTime. Now; // retrieves the current System date and time String dtt = dt. Year. ToString () + dt. Month. ToString () + dt. Day. ToString (); // retrieve the system date String filestr = "C: \ excel"; // filestr is the file path StringWriter stringWriter = new StringWriter (); HtmlTextWriter htmlWriter = new HtmlTextWriter (stringWriter ); Table1.RenderControl (htmlWriter ); String file = filestr + "\" + dtt + ". xls "; If (! Directory. Exists (filestr )) { Directory. CreateDirectory (filestr ); } System. IO. StreamWriter sw = new StreamWriter (file ); Sw. Write (stringWriter. ToString ()); Sw. Close ();
} } |