Tuesday, June 9, 2009

GridView Export into excel & Generate XML Dataset Values

DAL - Data Access Layer

static SqlConnection GetConnectionObject()
{
SqlConnection con = new SqlConnection();
string connectionstring;
try
{
connectionstring = ConfigurationManager.ConnectionStrings["logictest"].ConnectionString; ;
con.ConnectionString = connectionstring;

return con;
}
catch (Exception ex)
{
throw ex;
}

}

public static DataSet ExecuteSQLReturnDataSet(string strSQL)
{
DataSet ds = new DataSet("DataSet");
SqlConnection con = GetConnectionObject();
SqlDataAdapter da = new SqlDataAdapter(strSQL, con);
try
{
da.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
da.Dispose();
ds.Dispose();
}
}

GridView Export into excel:
Method to GeneratetheReport:

public void ReportGeneration(DataSet dset, string filename)
{

GridView gv = new GridView();
gv.DataSource = dset;
gv.DataBind(); //Read the grid value however the report format may be excel/pdf
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.OutputStream.Write(new byte[] { 0xef, 0xbb, 0xbf }, 0, 3);
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + filename + "");
HttpContext.Current.Response.ContentType = "application/ms-excel";
StringWriter oStringWriter = new StringWriter();
HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
gv.RenderControl(oHtmlTextWriter);
HttpContext.Current.Response.Write(oStringWriter.ToString());
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}

On btnclic/load event call the below method

void BindGridView()
{
DataSet ds = new DataSet();
ds = ExecuteSQLReturnDataSet("select * from tablename");
grd.DataSource = ds;
grd.DataBind();
if (ds.Tables[0].Rows.Count > 0)
{
ReportGeneration(ds, "Report.xls");
}
}
Generate XML Dataset Values:
public void XMLGenarate()
{
string XMLFileName = "C:/Projects/XMLGenerate" + DateTime.Now.ToString("dd-mm-yyyy") +""; // can set it in web.config
DataSet ds = new DataSet();
ds = ExecuteSQLReturnDataSet("select * from tableName"); // can pass it as a parameter of(string) / from Data Access Layer which has coding standard.
FileStream fs = null;
if (ds.Tables[0].Rows.Count > 0)
{
fs = new FileStream(XMLFileName + ".xml", FileMode.OpenOrCreate, FileAccess.Write);
ds.WriteXml(fs);
fs.Close();
}

}

on btnclick/load event call the above method.

Copyright © 2009 Angel