0

I am trying to convert a gridview into excel .xls but it throws error and when I click ok then it converts but the whole page appears in excel. I tried every content possible type, I have excel 2010.

Error:

the file you are trying to convert is in a different format than specified by the file extension

Code:

 protected void btnTransactionDetails_Click(object sender, EventArgs e)
    {
        try
        {
            LabelResult.Text = "";
            //GetReport();
            int BusID= Convert.ToInt32(DropDownListBuses.SelectedValue);
            int AccountID= Convert.ToInt32(DropDownList1.SelectedValue);
            DateTime FromDate = Convert.ToDateTime( FromDateTextBox.Text);
            DateTime ToDate = Convert.ToDateTime( ToDateTextBox.Text);
            DataTable dt= new DataTable();
            dt= Activities.GetLedger(AccountID, BusID, FromDate, ToDate);
            GridViewLedger.DataSource=  dt;
            GridViewLedger.DataBind();
            ViewState["Ledger"]= dt;

        }
        catch (Exception ex)
        {
            LabelResult.Text = ex.Message;
        }

    }

 protected void btnExportToExcel_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=LedgerReport_" + FromDateTextBox.Text + " To " + ToDateTextBox.Text + ".xls");
            Response.ContentType = "application/vnd.xlsx";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

            htmlWrite.Write("<table><tr><td colspan='4'><center>Report Date : " + FromDateTextBox.Text + " To " + FromDateTextBox.Text + "</center></td></tr></table>");
            GridViewLedger.AllowPaging = false;
            GridViewLedger.AllowSorting = false;
            //  showAttendance();
            GridViewLedger.DataSource = (DataSet)ViewState["Ledger"];
            GridViewLedger.DataBind();
            for (int i = 0; i <= GridViewLedger.Columns.Count - 1; i++)
            {

                GridViewLedger.HeaderRow.Cells[i].Style.Add("background-color", "#2FA4E7");
                GridViewLedger.HeaderRow.Cells[i].Style.Add("color", "#FFFFFF");

            }


            for (int i = 0; i < GridViewLedger.Rows.Count; i++)
            {
                GridViewRow row = GridViewLedger.Rows[i];

                row.Cells[3].Style.Add("background-color", "#73a839");
                row.Cells[3].Style.Add("color", "#FFFFFF");

                row.Cells[4].Style.Add("background-color", "#DA272D");
                row.Cells[4].Style.Add("color", "#FFFFFF");

            }

            GridViewLedger.RenderControl(htmlWrite);
            string style = @"<style> .textmode { mso-number-format:\@; } </style>";
            Response.Write(style);
            Response.Write(stringWrite.ToString());
            Response.End();
        }
        catch (Exception x)
        {
          //  ResultLabel.ResultLabelAttributes(x.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
        }
    }
Nima Derakhshanjan
  • 1,380
  • 9
  • 24
  • 37
Aamir Shah
  • 93
  • 1
  • 2
  • 14
  • 1
    Bind gridview from DataSet, after that search in google DataSet to Excel. – mybirthname Mar 02 '15 at 08:48
  • check this link http://www.aspsnippets.com/Articles/Export-GridView-to-Excel-in-ASPNet-with-Formatting-using-C-and-VBNet.aspx – santosh singh Mar 02 '15 at 08:52
  • Exporting Data Table to Excel you can try by using data table saved in ViewState["Ledger"]= dt;(as you are already saving your data table in viewstate) Please go through this http://stackoverflow.com/questions/8207869/how-to-export-datatable-to-excel-in-c-sharp – Keerthi Kumar Mar 02 '15 at 09:26
  • what about using .xlsx ? because you are using excel 2010 – Nima Derakhshanjan Mar 02 '15 at 09:38
  • you are saving an html file with xls extension. It is not a real xls file that is a binary file at its basics. You need an Excel library to save real Excel files. – alex.pulver Mar 03 '15 at 08:11

1 Answers1

0

Change this line

(DataSet)ViewState["Ledger"]; To (DataTable)ViewState["Ledger"];

You are trying to TypeCast DataTable to DataSet you will get following Exception

Unable to cast object of type 'System.Data.DataTable' to type 'System.Data.DataSet'.

Because ViewState["Ledger"] Contains data table(You have assigned data table to it)


I have created a sample project Its Exactly same as your code. Its working Fine For me Please Check

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable table = new DataTable();
            table.Columns.Add("Dosage", typeof(int));
            table.Columns.Add("Drug", typeof(string));
            table.Columns.Add("Patient", typeof(string));
            table.Columns.Add("Date", typeof(DateTime));

            // Here we add five DataRows.
            table.Rows.Add(25, "Indocin", "David", DateTime.Now);
            table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
            table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
            table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
            table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
            GridView1.DataSource = table;
            GridView1.DataBind();
            ViewState["Ledger"] = table;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=LedgerReport.xls");
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        htmlWrite.Write("<table><tr><td colspan='4'><center>Report Date </center></td></tr></table>");
        GridView1.AllowPaging = false;
        GridView1.AllowSorting = false;
        GridView1.DataSource = (DataTable)ViewState["Ledger"];
        GridView1.DataBind();
        for (int i = 0; i <= GridView1.Columns.Count - 1; i++)
        {
            GridView1.HeaderRow.Cells[i].Style.Add("background-color", "#2FA4E7");
            GridView1.HeaderRow.Cells[i].Style.Add("color", "#FFFFFF");

        }

        GridView1.RenderControl(htmlWrite);
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Write(stringWrite.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }
Keerthi Kumar
  • 168
  • 2
  • 13
  • Change the file name extension like this (.xls to .xlsx) Response.AddHeader("content-disposition", "attachment;filename=LedgerReport_" + FromDateTextBox.Text + " To " + ToDateTextBox.Text + ".xlsx") – Keerthi Kumar Mar 02 '15 at 10:06