Export to Excel not working

Having some problems exporting to Excel loadable content using AngularJS and ASP.NET MVC. My end results nothing happens.

Example ASP.NET Controller Method:

[HttpPost]
public ActionResult ExportToExcel(Model form)
{
    var gv = new GridView();
    gv.DataSource = _service.getSomeStuff(form);
    gv.DataBind();
    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=Stuff.xls");
    Response.ContentType = "application/ms-excel";
    Response.Charset = "";
    var sw = new StringWriter();
    var htw = new HtmlTextWriter(sw);
    gv.RenderControl(htw);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();

    byte[] temp = System.Text.Encoding.UTF8.GetBytes(sw.ToString());
    return File(temp, "application/ms-excel");
}

      

Angular Controller Method: -> triggered by ng-click handler

function exportToExcel() {
    $http.post('/Controller/ExportToExcel/', vm.Model)
           .success(function (data) {
           })
           .error(function (data) {
                alerts.error(data);
            });
}

      

View:

<a href="" ng-click="vm.exportToExcel()">click me</a>

      

Any suggestions on what I might be doing wrong?

+3


source to share


1 answer


I did something like this, without the need for AJAX or any JS. Tweaking the Razor code is all it takes.

Secondly, my personal suggestion would be not to convert to Excel file at all. The reason is that the user needs to have Office on their local machine. This also means that if you upload your project to a website, then the server computer will need Office to create your excel file.

That being said, I would suggest just using a CSV file. If the user has Office installed, they can use Excel to view the file like any spreadsheet.

Here is the code that will create a CSV called Export.csv from dbset in your dbcontext, done with StringBuilder

and Reflection

.



public ActionResult Export()
    {
        StringBuilder str = new StringBuilder();
        var tmp = db.Users.FirstOrDefault();     
        Type comp = tmp.GetType();                // get type
        foreach (PropertyInfo prop in comp.GetProperties())
        {
            str.Append(prop.Name + ",");          //set column names
        }
        str.Replace(",", "\n", str.Length - 1, 1);
        foreach (object item in db.Users)
        {
            foreach (PropertyInfo prop in item.GetType().GetProperties())
            {
                try
                {
                    string a = prop.GetValue(item, null).ToString();
                    str.Append(a + ",");
                }
                catch (NullReferenceException)
                {
                    str.Append("null" + ",");           //for nulls, append string with "null"
                }
            }
            str.Replace(",", "\n", str.Length - 1, 1);
        }
        string csv = str.ToString();
        return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Export.csv");
    }

      

Then you can upload a file with a link to your view like this:

<a href="@Url.Action("Export", "Controller")">click me</a>

      

Hope it helps.

0


source







All Articles