views:

26

answers:

1

I found code to export a datatable to excel, but I cant figure out how to get the controller to return the results.

any suggestions? here is the code

dt = city.GetAllCity();//your datatable 
    string attachment = "attachment; filename=city.xls"; 
    Response.ClearContent(); 
    Response.AddHeader("content-disposition", attachment); 
    Response.ContentType = "application/vnd.ms-excel"; 
    string tab = ""; 
    foreach (DataColumn dc in dt.Columns) 
    { 
        Response.Write(tab + dc.ColumnName); 
        tab = "\t"; 
    } 
    Response.Write("\n"); 
    int i; 
    foreach (DataRow dr in dt.Rows) 
    { 
        tab = ""; 
        for (i = 0; i < dt.Columns.Count; i++) 
        { 
            Response.Write(tab + dr[i].ToString()); 
            tab = "\t"; 
        } 
        Response.Write("\n"); 
    } 
    Response.End(); 
A: 

You can just return FileStreamResult:

public ActionResult DownloadCities()
{
    dt = city.GetAllCity();//your datatable 
    string attachment = "attachment; filename=city.xls";

    var writer = new StreamWriter(new MemoryStream());

    string tab = "";
    foreach (DataColumn dc in dt.Columns)
    {
        writer.Write(tab + dc.ColumnName);
        tab = "\t";
    }
    writer.Write("\n");
    int i;
    foreach (DataRow dr in dt.Rows)
    {
        tab = "";
        for (i = 0; i < dt.Columns.Count; i++)
        {
            writer.Write(tab + dr[i]);
            tab = "\t";
        }
        writer.Write("\n");
    }

    return File(writer.BaseStream, "application/vnd.ms-excel", "city.xls");
}
sheikhomar