在Asp.Net中打开下载的Excel工作表(.xls)时发生异常

时间:2013-07-31 12:04:43

标签: asp.net

我使用以下代码下载Excel表格。 enter image description here

上面的代码启动了我的逻辑代码。下载后,我打开Excel Sheet.It显示这样的警告

enter image description here

由于此警告,当我尝试使用Asp.Net将同一页面上传到Mysql DataBase时,会显示“页面格式不正确”等异常。

这是我下载Excel表格的完整逻辑

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();
}

所以请给我建议如何下载Excel表格,而不会在打开时显示错误。

1 个答案:

答案 0 :(得分:1)

您正在生成csv文件,而不是excel文件。尝试更改标题:

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

通常,excel是打开csv文件的默认设置。