protected void btnExport_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt = Session["data"] as DataTable; if (dt == null) { throw new Exception("No Records to Export"); } string Path = "D:\\ImportExcelFromDatabase\\Karvyexcel_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + ".xls"; //string Path = "D:\\Sujatha\\Karvy_27Nov2012\\Inventory_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + ".xls"; FileInfo FI = new FileInfo(Path); StringWriter stringWriter = new StringWriter(); HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter); DataGrid DataGrd = new DataGrid(); DataGrd.DataSource = dt; DataGrd.DataBind(); DataGrd.RenderControl(htmlWrite); ////string directory = Path.Substring(0, Path.LastIndexOf("\\"));// GetDirectory(Path); ////if (!Directory.Exists(directory)) ////{ //// Directory.CreateDirectory(directory); ////} //System.IO.StreamWriter vw = new System.IO.StreamWriter(Path, true); stringWriter.ToString().Normalize(); //vw.Write(stringWriter.ToString()); //vw.Flush(); //vw.Close(); WriteAttachment(FI.Name, "application/vnd.ms-excel", stringWriter.ToString()); } public static void WriteAttachment(string FileName, string FileType, string content) { HttpResponse Response = System.Web.HttpContext.Current.Response; Response.ClearHeaders(); Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName); Response.ContentType = FileType; Response.Write(content); Response.End(); } private void BindCustomerData() { try { string strSelect = "select * from CustomerData"; DataSet ds = new DataSet(); cnn.ConnectionString = connStr; // if the connection will be closed the below code poen the connection when the page will be loaded. if (cnn.State == ConnectionState.Closed) { cnn.Open(); } // here i am using the store procedure named tb_gallery_insert to insert the record inside the database. SqlDataAdapter da = new SqlDataAdapter(strSelect, cnn); da.Fill(ds); if (ds.Tables[0].Rows.Count > 0) { gvData.DataSource = ds.Tables[0]; gvData.DataBind(); Session["data"] = ds.Tables[0]; } else { lblMessage.Text = "No Records Found"; lblMessage.ForeColor = System.Drawing.Color.Red; } } catch (Exception ex) { lblMessage.Text = ex.Message; lblMessage.ForeColor = System.Drawing.Color.Red; } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)