GridView column freeze to export xls - c#

In my web project I download an xls file.
I generate a gridview with the data I need and download.
Once I open the excel, I need a column to be blocked.
My code is as follows:
private DataTable tableExcel;
public ActionResult returnExcel(HttpResponseBase response, string name)
{
var grid = new GridView();
grid.DataSource = tableExcel;
grid.DataBind();
GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell HeaderCell = new TableCell();
HeaderCell = new TableCell();
HeaderCell.Text = h.text;
HeaderCell.ColumnSpan = colunesSpan;
HeaderCell.Font.Bold = h.negreta;
HeaderCell.HorizontalAlign = h.aliniacio;
HeaderGridRow.Cells.Add(HeaderCell);
HeaderGrid.Controls[0].Controls.AddAt(0, HeaderGridRow);
response.ClearContent();
response.Buffer = true;
response.AddHeader("content-disposition", $"attachment; filename={name}.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();
}
The code works correctly, the only thing I need is to be able to implement the option to block or freeze a column.
grid.Columns[0].Frozen = true;
grid.Rows[0].CssClass = "locked";
I found these solutions but they do not work for GridView.

Related

How to add dropdown list in gridview excel export

Currently my method is use for export excel file from gridview. Now I want to create dropdown list in some column for each row of excel file. It's possible to do with StringWriter?
There is my code of the method...
string exportFileName = Session["corpUser"].ToString() + "_ProjectExport_" + unixTimestamp + ".xls";
//Create a dummy GridView
GridView dummyGridView = new GridView();
dummyGridView.AllowPaging = false;
dummyGridView.DataSource = dt;
dummyGridView.DataBind();
//Write Dummy Gridview to Excel File
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + exportFileName);
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
dummyGridView.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();

export large list<> to excel C# MVC

I want to export a list with over 10000 rows to excel using MVC5 C#.
when I export using DataGrid some columns are not shown in the excel file - 3 columns are disapeard in the excel file but all the 10000 rows appeard.
string filename = Guid.NewGuid() + ".xls";
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
List registrationsetList = db.RegistrationSet.Where(x => x.QuestionId == TheQuestion.Id).ToList();
dgGrid.DataSource = registrationsetList;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.Write(tw.ToString());
Response.End();
If I change DataGrid dgGrid = new DataGrid()
to GridView dgGrid = new GridView();
with list of 600 of rows, the excel looks perfect with all the columns.
the problem is when i export all the list of 10000 rows, the excel file got stuck - i got not responding message.
why ?
Instead of using a DataGrid() try using a WebControl GridView():
string filename = Guid.NewGuid() + ".xls";
var gv = new System.Web.UI.WebControls.GridView();
var registrationsetList = db.RegistrationSet.Where(x => x.QuestionId == TheQuestion.Id);
g.DataSource = registrationsetList;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + filename);
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWiter sw = new StringWriter();
var htw = new System.Web.UI.HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
The problem (with that stucked excel file) was solved with DataGrid. The problem was that the DateGrid doen't show columns of nullable fields in the CLASS in the list that i bound to the GridView.

Export data from gridview to excel without losing the gridlines

I am trying to export to excel the grid view data.I could bind the data in excel.However when I open the grid view I am losing its grid lines which looks really bad. I have added my code below.
This code takes my grid data and exports it to excel deleting all the gridlines i tried to google couldnt find a breaktrough can someone help me with this
protected void btn_export_Click(object sender, EventArgs e)
{
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName = "Dashboard_FOR_PM" + DateTime.Now + ".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
grv_dashboard.GridLines = GridLines.Both;
grv_dashboard.HeaderStyle.Font.Bold = true;
grv_dashboard.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
Table table = new Table();
table.BorderStyle = BorderStyle.Solid;
table.BorderWidth=new Unit(1);
table.BorderColor = System.Drawing.Color.Black;
table.GridLines = GridLines.Both;
}
}
strwritter.Write(#"<html xmlns:x=""urn:schemas-microsoft-com:office:excel"">");
strwritter.Write(#"<head>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:WorksheetOptions>
<x:Panes></x:Panes>
<x:Print><x:Gridlines /></x:Print>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
</head>");
Response.End();
}
have a look at below function that I wrote before,please ask if something is unclear,hope it helps
public void ToExcel(DataTable dt, string reportName)
{
if (dt.Rows.Count > 0)
{
string filename = string.Format("{0}.xls", reportName);
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
HtmlForm hf = new HtmlForm();
DataGrid dg = new DataGrid();
dg.DataSource = dt;
dg.HeaderStyle.BackColor = Color.Tomato;//change to your own colors
dg.HeaderStyle.ForeColor = Color.White;//change to your own colors
dg.BackColor = Color.LightGoldenrodYellow;//change to your own colors
dg.AlternatingItemStyle.BackColor = Color.PaleGoldenrod;//change to your own colors
dg.Font.Name = "Tahoma";
dg.Font.Size = 10;
dg.GridLines = GridLines.Both;
dg.BorderColor = System.Drawing.Color.Black;
dg.BorderStyle = BorderStyle.Solid;
dg.BorderWidth = new Unit(1);
dg.DataBind();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
HttpContext.Current.Response.Charset = "";
EnableViewState = false;
Controls.Add(hf);
hf.Controls.Add(dg);
hf.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}

Export to Excel not working in ASP.NET MVC 4

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.

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