0

I have a requirement for export data to excel using open Xml plug in. And I want to style excel head boarder colour. I tried different method to achieve my requirement. I would like to export my data table to excel.

My Code as follows

 public ActionResult ExportToExcel()
        {
            var products = new System.Data.DataTable("teste");
            products.Columns.Add("Name", typeof(string));
            products.Columns.Add("Age", typeof(int));
            products.Columns.Add("Gender", typeof(string));
            products.Columns.Add("Salary", typeof(int));
            products.Rows.Add("Basil", 34, "male", 40000);
            products.Rows.Add("Varghese", 34, "male", 40000);
            products.Rows.Add("George", 34, "male", 40000);
            products.Rows.Add("John", 34, "male", 40000);


            var grid = new GridView();
            grid.DataSource = products;
            grid.DataBind();

            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
            Response.ContentType = "application/ms-excel";

            Response.Charset = "";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            grid.RenderControl(htw);

            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();

            return View("MyView");
        }
ArunPratap
  • 4,816
  • 7
  • 25
  • 43
  • 4
    Start using a specialized library for creating Excel files, like [EPPlus](https://github.com/JanKallman/EPPlus). [Example here](https://stackoverflow.com/a/47293207/5836671) and [here](https://stackoverflow.com/a/39513057/5836671). All you are doing now is creating a HTML page with an .xls extension. – VDWWD Mar 22 '19 at 12:34
  • 1
    I want to use using DocumentFormat.OpenXml.Packaging Simply iam a beginner –  Mar 22 '19 at 12:38
  • Why do you want to use that specifically? Why do you care, as long as it works? – ADyson Mar 22 '19 at 20:14
  • 1
    The work is already done using open XML. I would like to modify that. –  Mar 23 '19 at 06:27
  • What work? The code above is not using openXML. If you have some other code you want to modify, please show it and explain the problem – ADyson Mar 23 '19 at 10:34

0 Answers0