Export to Excel not working in ASP.NET MVC 4 - c#

I have a code that will generate an excel report.i am using ASP.NET MVC 4. I googled and found the same code everywhere still my code is not working why. My code in controller is as:
public ActionResult ExportData()
{
string[] abc = { "AAA", "BBB", "CCC" };
GridView gv = new GridView();
gv.DataSource = abc;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Marklist.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("_EligibilityCriteria");
}
Just to test the export functionality I used an array abc this code is working in .net application but not in ASP.NET MVC 4 application. I have debugged the code but not found a problem or error in code.
What am I doing wrong here?

Finally found a way to export to excel.
public void ExportIniEmployeeToExcel(EligibilityCriteriaModel AllIniEmp)
{
List<AllIniEmployees> emp = new List<AllIniEmployees>();
AllIniEmp.allSuccessEmployeeList.ForEach(x =>
{
AllIniEmployees allEmp = new AllIniEmployees();
allEmp.EmployeeCode = x.EmployeeCode;
allEmp.EmployeeName = x.EmployeeName;
allEmp.Designation = x.Designation;
allEmp.DeliveryTeam = x.DeliveryTeam;
allEmp.ConfirmationDate = x.ConfirmationDate;
emp.Add(allEmp);
});
GridView gv = new GridView();
gv.DataSource = emp;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=InitiatedEmployees.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
here i used parent class as a parameter and used linq.now its working perfectly fine.
thank you all.

You can't just write the output with a StringWriter. After your call to RenderControl, write:
byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
MemoryStream s = new MemoryStream(byteArray);
StreamReader sr = new StreamReader(s, Encoding.ASCII);
Response.Write(sr.ReadToEnd());
Response.End();

Try returning a ContentResult instead of writing directly to the output stream.

Related

The file format and extension dont match when using closexml?

I have a working method, that export to excel, but the issue is file extension is not support and being not format. This is not user friendly, how can I improve this from not allow a user to see this issue?
// controller
public void ExportToExcel()
{
var v = new GridView();
v.DataSource = this.GetExtractionViewModels();
v.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=ExtractionRecords.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter objStringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(objStringWriter);
v.RenderControl(htmlTextWriter);
Response.Output.Write(objStringWriter.ToString());
Response.Flush();
Response.End();
//return View("DataResult");
}

Excel file export nothing happens with no error

I have trying to export my data from my data access layer
but nothing happens no error and not exported.
it is kinda hard to know whats wrong because there's no error
I have tried this:
if (dt.Rows.Count > 0){
dgv.DataSource = dt;
dgv.DataBind();
Response.ClearContent();
Response.AppendHeader("content-disposition","attachement;filename=transaction.xls");
Response.ContentType = "application/excel";
StringWriter stringWritter = new StringWriter();
HtmlTextWriter htmlTextWritter = new HtmlTextWriter(stringWritter);
dgv.RenderControl(htmlTextWritter);
Response.Write(stringWritter.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
butnothing happens.
i have tried this but also nothing:
StringWriter osStringWritter = new StringWriter();
Html32TextWriter osHtmlTextWritter = new Html32TextWriter(osStringWritter);
DataTable dt = new DataTable();
DataGrid dgv = new DataGrid();
Response.Clear();
Response.Buffer = false;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", "TransactionReport"));
Response.Charset = "";
dgv.DataSource = dt;
dgv.DataBind();
dgv.RenderControl(osHtmlTextWritter);
Response.Write("Report Datw:" + DateTime.Now);
Response.Write(osStringWritter.ToString());
//Response.End();
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
dgv = null;
osStringWritter = null;
osHtmlTextWritter = null;
What i'm doing wrong ?
Try this may resolve your issue
dgv.DataSource = dt;
dgv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename = Export to Excel.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
dgv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}

Xls Export in not running on the server

public ActionResult ExportToExcel()
{
GridView gv = new GridView();
gv.DataSource = db.Details.Select(x => new
{
x.Title,
Category = x.Category.Title,
SubCategory = x.SubCategory.Title,
x.Count,
x.Price,
Automobiles = x.Automobiles.Count,
x.Description
}).ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Marklist.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return Json(true);
}
Export works well locally . It does not work on Azure. Downloading an empty file . Tell me what's the problem ?
Your issue might be related to the recent Microsoft Security Update for Excel.
See... https://stackoverflow.com/a/38467132/6610346

asp.net export to Excel UTF-8

Here is my code :
var model = _db.FacebookInfo.OrderByDescending(f => f.Followers).ToList();
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = (from u in model
select new
{
fullname = System.Text.RegularExpressions.Regex.Replace(u.FullName, "<span .*?>(.*?)", ""),
followers = u.Followers,
friends = u.Friends,
url = u.FbLink
}).ToList();
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=Nana bregvadze Friends.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
It just create an excel file, but i have an unicode problem, can't read Georgian charachters. Look at the picture :
Maybe it's a duplicate but no solution worked for me.
Your code doesn't create a real XLSX file, it creates an HTML table with a faked header and extension. Excel will import this file using the end user's default settings and locale.
Instead of faking Excel files, you can easily create a real XLSX file with minimal code using a library like EPPlus. There's even a Web Application example in the Codeplex site. You can use LoadFromCollection instead of LoadFromDataTable in your case:
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
var ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1.
// Print the column names on row 1
var table=ws.Cells["A1"].LoadFromCollection(model, true);
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
Note that table is an actual ExcelRange object, that can be given a name, style etc.
Okey i solve the problem :
just change Response.ClearContent() to Response.Clear() and add
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />")
full code :
var model = _db.FacebookInfo.OrderByDescending(f => f.Followers).ToList();
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = (from u in model
select new
{
fullname = System.Text.RegularExpressions.Regex.Replace(u.FullName, "<span .*?>(.*?)", ""),
followers = u.Followers,
friends = u.Friends,
url = u.FbLink
}).ToList();
grid.DataBind();
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Nana bregvadze Friends.xls");
Response.ContentType = "application/excel";
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

Excel export is not working with WebControl table

in my application i have bind sql data source to grid view, on click of export button i took gridviews datasource in datatable and created webControl table and write that control to xls file. but i am getting follwowing error:
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
My code is as follows:
HttpResponse Response = HttpContext.Current.Response;
Response.Clear();
string StudNm = Request["hidStudnm"];
Response.AddHeader("content-disposition", "attachment;filename=" + "StudentPasswordReport" + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
System.Web.UI.WebControls.Table tblRept;
tblRept = CreateTable(exportDt);
tblRept.RenderControl(htmlWrite);
please tell me why this error is occurred and how can i resole this error
You could try this
DataTableToExcel(exportDt);
private void DataTableToExcel(DataTable dataTable)
{
StringWriter writer = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
GridView gridView = new GridView();
gridView.DataSource = dataTable;
gridView.AutoGenerateColumns = true;
gridView.DataBind();
gridView.RenderControl(htmlWriter);
htmlWriter.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Write(writer.ToString());
Response.End();
}

Categories

Resources