c# - Export to Excel not working -



c# - Export to Excel not working -

having problem exporting downloadable excel content, using angularjs & asp.net mvc. end results nil happens.

sample 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()); homecoming file(temp, "application/ms-excel"); }

angular controller method: -> triggered via 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 of might doing wrong?

i have done this, without need ajax or js. tweaking razor code required.

secondly, personal suggestion not convert excel file @ all. reason being, user required have office on local machine. means, should upload project website, server machine need office installed in order produce excel file.

that beingness said, suggest using csv file. if user has office installed, able utilize excel view file spreadsheet.

here code create csv called export.csv dbset in dbcontext, done using stringbuilder , reflection.

public actionresult export() { stringbuilder str = new stringbuilder(); var tmp = db.users.firstordefault(); type comp = tmp.gettype(); // 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()) { seek { string = prop.getvalue(item, null).tostring(); str.append(a + ","); } grab (nullreferenceexception) { str.append("null" + ","); //for nulls, append string "null" } } str.replace(",", "\n", str.length - 1, 1); } string csv = str.tostring(); homecoming file(new system.text.utf8encoding().getbytes(csv), "text/csv", "export.csv"); }

you can access download file link on view this:

<a href="@url.action("export", "controller")">click me</a>

hope helps.

c# asp.net asp.net-mvc angularjs excel

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -