Export data to Excel file with ASP.NET MVC 4 C# is rendering into view -
i having trouble exporting data excel. following seems render gridview view, instead of prompting user open excel, have installed on machine.
public actionresult exporttoexcel() { var products = this.repository.products.tolist(); var grid = new gridview(); grid.datasource = p in products select new { id = p.id, name = p.name }; grid.databind(); response.clearcontent(); response.buffer = true; response.addheader("content-disposition", "attachment; filename=myexcelfile.xls"); response.contenttype = "application/ms-excel"; response.charset = ""; stringwriter sw = new stringwriter(); htmltextwriter htw = new htmltextwriter(sw); grid.rendercontrol(htw); response.output.write(sw.tostring()); response.flush(); response.end(); return view("myview"); }
what doing wrong?
i have tried code , works fine. file being created without problem, code used (it's code, changed datasource testing):
public actionresult exporttoexcel() { var products = new system.data.datatable("teste"); products.columns.add("col1", typeof(int)); products.columns.add("col2", typeof(string)); products.rows.add(1, "product 1"); products.rows.add(2, "product 2"); products.rows.add(3, "product 3"); products.rows.add(4, "product 4"); products.rows.add(5, "product 5"); products.rows.add(6, "product 6"); products.rows.add(7, "product 7"); var grid = new gridview(); grid.datasource = products; grid.databind(); response.clearcontent(); response.buffer = true; response.addheader("content-disposition", "attachment; filename=myexcelfile.xls"); response.contenttype = "application/ms-excel"; response.charset = ""; stringwriter sw = new stringwriter(); htmltextwriter htw = new htmltextwriter(sw); grid.rendercontrol(htw); response.output.write(sw.tostring()); response.flush(); response.end(); return view("myview"); }
Comments
Post a Comment