Ajay
Ajay

Reputation: 2080

Exception Occurs While Opening a Downloaded Excel Sheet(.xls) In Asp.Net

I download an Excel Sheet by using the following code. enter image description here

The above code is starting code of my logic.After downloaded, I open the Excel Sheet.It shows an Warning like this

enter image description here

Because of this warning,when Im trying to upload the same page to Mysql DataBase using Asp.Net.It shows an Exception like "Page is not in correct Format".

This Is My Entire Logic For Downloading an Excel Sheet

protected void download_Click(object sender, EventArgs e)
 {

    ExportToExcel(SqlDataSource1, "StudentMarks");
  }
public void ExportToExcel(SqlDataSource dataSrc, string fileName)
{
    //Add Response header 
    Response.Clear();
    Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
    Response.Charset = "";
    Response.ContentType = "application/ms-excel";
    //GET Data From Database                
    MySqlConnection cn = new MySqlConnection(dataSrc.ConnectionString);
    // string query =  dataSrc.SelectCommand.Replace("\r\n", " ").Replace("\t", " ");
    MySqlCommand cmd9 = new MySqlCommand("select subject from class_subject where standard='" + DropDownList1.SelectedItem.Value + "';", cn);
    // cn.Open();

    //DataSet ds9=new DataSet();
    MySqlDataAdapter da9 = new MySqlDataAdapter(cmd9);
    // da9.Fill(ds9);
    DataTable dt = new DataTable();
    da9.Fill(dt);

    StringBuilder sb9 = new StringBuilder();




    for (int count = 0; count < dt.Rows.Count; count++)
    {
        // string headerRowText = GridView4.HeaderRow.Cells[i].Text;
        sb9.Append("'");
        sb9.Append(dt.Rows[count][0].ToString());
        sb9.Append("'");
        if (count < dt.Rows.Count - 1)
        //if (count < count3 - 1)
        {
            sb9.Append(",");
        }
    }
    Label2.Text = sb9.ToString();
    //MySqlCommand fyearcmd = new MySqlCommand("select fyear from student_data where standard='" + DropDownList1.SelectedItem.Value + "' and completed_status='running';", cn);
    //MySqlDataReader fyeardr = fyearcmd.ExecuteReader();

    string query = "select Admission_Num,Name,'Standard','Fyear','Type_of_exam'," + sb9.ToString() + " from student_data where standard='" + DropDownList1.SelectedItem.Value + "' and fyear='" + DropDownList4.SelectedItem.Value + "';";

    MySqlCommand cmd = new MySqlCommand(query, cn);

    cmd.CommandTimeout = 999999;
    cmd.CommandType = CommandType.Text;
    try
    {
        cn.Open();
        MySqlDataReader dr = cmd.ExecuteReader();
        StringBuilder sb = new StringBuilder();
        //Session["fieldcount"] = dr.FieldCount.ToString();
        //Label1.Text = dr.FieldCount.ToString();
        //Add Header  
        int count3 = 4;
        for (int count = 0; count < dr.FieldCount; count++)
        //for (int count = 0; count < count3; count++)
        {
            if (dr.GetName(count) != null)
                sb.Append(dr.GetName(count));
            if (count < dr.FieldCount - 1)
            //if (count < count3 - 1)
            {
                sb.Append("\t");
            }
        }
        Response.Write(sb.ToString() + "\n");
        Response.Flush();
        //Append Data
        while (dr.Read())
        {
            sb = new StringBuilder();

            //for (int col = 0; col < dr.FieldCount - 1; col++)
            for (int col = 0; col <= count3; col++)
            {
                if (col < (count3 - 2))
                {

                    if (!dr.IsDBNull(col))
                        sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
                    sb.Append("\t");
                }
                if (col == (count3 - 2))
                {

                    if (!dr.IsDBNull(col))
                        sb.Append(DropDownList1.SelectedItem.Text);
                    sb.Append("\t");
                }
                if (col == (count3 - 1))
                {
                    if (!dr.IsDBNull(col))
                    {
                        //sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
                        sb.Append(DropDownList4.SelectedItem.Text);
                    }
                    sb.Append("\t");
                }
                if (col == count3)
                {
                    if (!dr.IsDBNull(col))
                    {
                        //sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
                        sb.Append(DropDownList3.SelectedItem.Text);
                    }
                    sb.Append("\t");
                }
            }
            //if (!dr.IsDBNull(dr.FieldCount - 1))
            //    sb.Append(dr.GetValue(dr.FieldCount - 1).ToString().Replace(",", " "));
            Response.Write(sb.ToString() + "\n");
            Response.Flush();

        }
        dr.Dispose();
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
    finally
    {
        cmd.Connection.Close();
        cn.Close();
    }
    Response.End();
}

So Please give me the suggestion how to download the Excel Sheet with out showing errors while opening.

Upvotes: 0

Views: 293

Answers (1)

Peter
Peter

Reputation: 27944

You you are generating a csv file, not a excel file. Try to change you header:

Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");

Normally excel is default for opening csv files.

Upvotes: 1

Related Questions