Domanda

I'm trying to export a DataTable into an Excel spreadsheet from a MVC web app. I'm trying to make this method "generic," in that any other controller from multiple web apps (contained in the same VS solution) can call and use it. I've done this by placing this within a separate controller used solely for this purpose.

When this method is embedded in a functional controller, it works fine. However, I'm getting NullPointerExceptions on the Response.Clear() function. Is it possible to get this to work in a standalone controller, or will it have to run within a functional controller?

Here's my code:

public ActionResult ExportFromDB(string sqlQuery)
    {
        DataTable dt = new DataTable();

        using (OleDbConnection conn = connectionString)
        {
            OleDbCommand cmd = new OleDbCommand(sqlQuery, conn);

            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
            adapter.Fill(dt);
        }

        GridView GridView1 = new GridView();
        GridView1.AllowPaging = false;
        GridView1.DataSource = dt;
        GridView1.DataBind();
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=DataTable.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            //Apply text style to each Row
            GridView1.Rows[i].Attributes.Add("class", "textmode");
        }
        GridView1.RenderControl(hw);
        //style to format numbers to string
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();

        return RedirectToRoute("back to home controller");
    }
È stato utile?

Soluzione

You can change your method to pass the HttpContext to it:

public ActionResult ExportFromDB(HttpContext context, string sqlQuery)
{
    //...
    context.Response.Clear();
}

And pass the current contect every time you use this method.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top