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();
}
}
Related
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();
}
}
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.
I have to export two gridview in two different excel,
but while exporting i getting exception on Respose.end() of first gridview (System.Threading.ThreadAbortException).
{//export firstgrid
Response.ClearContent();
Response.ClearHeaders();
DataTable dtGetReportBank = new DataTable();
dtGetReportBank = objPO.GetReportBank(id);
gridData1.DataSource = dtGetReportBank;
gridData1.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "BankCMS" + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw1 = new StringWriter();
HtmlTextWriter htw1 = new HtmlTextWriter(sw1);
gridData1.AllowPaging = false;
dvContent.RenderControl(htw1);
Response.Write(sw1.ToString());
Response.End();
Btn.Visible = false;
}
//export second grid
{
Response.ClearContent();
Response.ClearHeaders();
DataTable dtGetReportBank = new DataTable();
dtGetReportBank = objPO.GetReportBank(id);
gridData.DataSource = dtGetReportBank;
gridData.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "BankCMS" + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw1 = new StringWriter();
HtmlTextWriter htw1 = new HtmlTextWriter(sw1);
gridData.AllowPaging = false;
dvContent.RenderControl(htw1);
Response.Write(sw1.ToString());
Response.End();
Btn.Visible = false;
}
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.
I am exporting a GridView to an Excel file, but when I open
the file, first I get an error regarding the fact that
the format type and extension don't match, and when I open it
the whole page is brought into the Excel file, not just the grid view.
I'm not using an Update Panel. I tried with the button inside the GridView and outside
and the same result, so it seems it might be something from the code-behind which
looks like this:
Response.Clear();
Response.Buffer = true;
string filename = "GridViewExport_" + DateTime.Now.ToString() + ".xls";
Response.AddHeader("content-disposition",
"attachment;filename=" + filename);
Response.Charset = String.Empty;
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView3.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
You can try this method:
void ExportDataSetToExcel(GridView grdData, string filename)
{
grdData.BorderStyle = BorderStyle.Solid;
grdData.BorderWidth = 1;
grdData.BackColor = Color.WhiteSmoke;
grdData.GridLines = GridLines.Both;
grdData.Font.Name = "Verdana";
grdData.Font.Size = FontUnit.XXSmall;
grdData.HeaderStyle.BackColor = Color.DimGray;
grdData.HeaderStyle.ForeColor = Color.White;
grdData.RowStyle.HorizontalAlign = HorizontalAlign.Left;
grdData.RowStyle.VerticalAlign = VerticalAlign.Top;
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "";
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename+ "\"");
using (var sw = new StringWriter())
{
using (var htw = new HtmlTextWriter(sw))
{
grdData.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
USE this code: This will work fine..
aspx code::
<%# Page Language="C#" AutoEventWireup="true" CodeFile="default.aspx.cs" Debug ="true" enableEventValidation ="false" Inherits="default"%>
Here is the aspx code :
protected void ConvertToExcel_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Report.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
{
GridView1.HeaderRow.Cells[i].Style.Add("background-color", "#bfc2c7");
}
int j = 1;
foreach (GridViewRow gvrow in GridView1.Rows)
{
if (j <= GridView1.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
Solved !!!
your code is correct only problem with Response.Flush(); using in the code
instead of Response.Flush(); you should use Response.End();
Below is the working code:
Response.Clear();
Response.Buffer = true;
string filename = "GridViewExport_" + DateTime.Now.ToString() + ".xls";
Response.AddHeader("content-disposition",
"attachment;filename=" + filename);
Response.Charset = String.Empty;
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView3.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
// Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();