0

Below is my code used to export the excel file.

public void ExportReport()
    {
        DataTable dataTable = new DataTable();
        dataTable = getDataTable();
        HttpResponse response = HttpContext.Current.Response;
        GridView grdExportData = new GridView();

        grdExportData.AllowPaging = false;
        grdExportData.DataSource = dataTable;
        grdExportData.DataBind();

        //Clear the response and add the content types and headers to it.
        response.Clear();
        response.ClearContent();
        response.ContentType = "application/octet-stream";
        DateTime currDate = DateTime.Now;
        response.AddHeader("Content-Disposition", "attachment; filename=report.xls")

        // Create a dynamic control, populate and render it
        GridView excel = new GridView();
        excel.DataSource = dataTable;
        excel.DataBind();
        HtmlTextWriter htmlTextWriter = new HtmlTextWriter(response.Output);
        htmlTextWriter.Write("<table><tr><td colspan='3'><b>Report Title</b></td><td colspan='1'></td><td colspan='1'><b>Date: &nbsp;</b></td><td colspan='1'>" + DateTime.Today.ToString("MM/dd/yyyy") + "</td></tr></table>");
        excel.RenderControl(htmlTextWriter);
        response.Flush();
        response.End();
    }

Code works and exported the report but when I modify the excel sheet in "ms excel" and try to save the file it saved as web page format. I want default format as Excel.

Thanks in advance.

Manishmz
  • 9
  • 1
  • 2
    You are not creating an Excel file, you are creating an HTML file with an Excel extension. (Excel should warn of this problem on open/save) If you want the file to behave as a true XLS would you need to create a true XLS file. – Alex K. May 30 '17 at 12:54
  • An alternative would be to CSV. – PaulF May 30 '17 at 13:32
  • I searched but I didn't find anything to create a true XLS file. Do you know how to create a true XLS file? – Manishmz Jul 27 '17 at 08:46
  • Possible duplicate of [Create Excel (.XLS and .XLSX) file from C#](https://stackoverflow.com/questions/151005/create-excel-xls-and-xlsx-file-from-c-sharp) – Christian Gollhardt Sep 27 '17 at 20:06

1 Answers1

1

You need to change the ContentType.

For .xls files it is "application/vnd.ms-excel"

Kalamarico
  • 5,466
  • 22
  • 53
  • 70
g0np
  • 191
  • 1
  • 10