Search code examples
asp.netexcelexportstimulsoft

What is the best way to create .xls from datatable in asp .Net c#?


i have a datatable and i want to export excel from that, my datatable contains unicode characters (persian characters) and i want to convert it to .xls files correctly. i was wonder is it possible to do that with Stimulsoft?


Solution

  • This is a common method I use

           public void ExportDetails(DataTable tempDataTable, string FileName)
                {
                    try
                    {
                        System.IO.StringWriter objStringWriter1 = new System.IO.StringWriter();
                        System.Web.UI.WebControls.GridView gridView1 = new System.Web.UI.WebControls.GridView();
                        System.Web.UI.HtmlTextWriter objHtmlTextWriter1 = new System.Web.UI.HtmlTextWriter(objStringWriter1);
    
                        HttpContext.Current.Response.ClearContent();
                        HttpContext.Current.Response.ClearHeaders();
                        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
                        HttpContext.Current.Response.Charset = "";
                        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
                        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
                        Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
                        gridView1.DataSource = tempDataTable;
                        gridView1.DataBind();
    
                        gridView1.HeaderStyle.Font.Bold = true;
                        gridView1.HeaderStyle.BackColor = System.Drawing.Color.Gray;
    
                        gridView1.RenderControl(objHtmlTextWriter1);
    
                        gridView1.Dispose();
                        HttpContext.Current.Response.Write(objStringWriter1.ToString());
    
                        HttpContext.Current.Response.End();
                    }
                    catch (Exception ex)
                    {
    
    
                    }
    }