2014年7月13日 星期日

[RESOLVED] Exporting datalist and gridview to excel


Hello Experts,


I am having one datalist and gridview within datalist control. I need to export both of them as report in excel sheet. Like below


sr.  Class  CreatedDate ModifiedDate


1     Class1   25/5/2013   25/5/2013


Students


Sr.  Name Address Bdate


1    Abc    test add  25/5/1990


2    DEF   test add 2  25/3/1991


sr.  Class  CreatedDate ModifiedDate


2     Class2   25/6/2013   25/6/2013


Students


Sr.  Name Address Bdate


1    Abc2    test add22  25/5/1990


2    DEF2   test add 22  25/3/1991


and so on.....


Here the class display is datalist and student display is gridview.


Please suggest how to achive that?


Thank you.




Refer bellow url


http://www.aspsnippets.com/Articles/Export-GridView-To-WordExcelPDFCSV-in-ASP.Net.aspx



Hi,


Please try to refer to the following code about export data to excel (use the gridview as an example):


protected void fillGrid()
{
string str = "SELECT [UNo], [EmpName], [Age],
convert(char,[dob],103) dob FROM [tbl_EmpDetails]";

myConnection = new SqlConnection(conn);
myConnection.Open();
myCommand = new SqlCommand(str, myConnection);
SqlDataAdapter mySQLDataAdapter;
myDataSet = new DataTable();
mySQLDataAdapter = new SqlDataAdapter(myCommand);
mySQLDataAdapter.Fill(myDataSet);
GridView1.DataSource = myDataSet;
GridView1.DataBind();
ViewState["dtList"] = myDataSet;
}

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillGrid();
}
}

Now, after binding a Gridview, data is ready to get exported to an Excel file. Click on a button named Export to Excel. Used FileInfo to get the information related to the file.


FileInfo FI = new FileInfo(Path);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid DataGrd = new DataGrid();
DataGrd.DataSource = dt1;
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());

The above code uses a WriteAttachment function which pushes the attachment to the user in the Response object. The following code shows the implementation of WriteAttachment:


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();
}

Hope it can help you.


Best Regards,

Amy Peng 


沒有留言:

張貼留言