using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
BindGridview();
}
}
public void BindGridview()
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data source=" + Server.MapPath("Bin/MyDatabase.mdb") + "";
con.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM MyTable", con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
gdvMyGridView.DataSource = dt;
gdvMyGridView.DataBind();
ViewState["ExportReport"] = dt;
}
protected void btnExport_Click(object sender, EventArgs e)
{
try
{
DataTable dt = null;
dt = (DataTable)ViewState["ExportReport"];
if (dt == null)
{
throw new Exception("No record found for export");
}
string Path = "D:\\ImportDailCallReport\\myexcelfile_" + 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("\\"));
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());
}
catch (Exception ex)
{
}
finally
{
}
}
public static void WriteAttachment(string FileName, string FileType, string content)
{
try
{
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.ContentType = FileType;
Response.Write(content);
Response.End();
}
catch (Exception ex)
{
}
}
}