Gridview not getting last row in the Excel file - asp.net

I wrote a code to fetch the gridview to the Excel. Everything is working fine except a row in the gridview. When i export gridview to excel, then last row doesnot includes in the excel file. When i scanned my whole code, then i found a code which is creating a problem. Here is the code :
protected void OnDataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
TableHeaderCell cell = new TableHeaderCell();
cell.Text = "A";
cell.ColumnSpan = 9;
row.Controls.Add(cell);
gv.HeaderRow.Parent.Controls.AddAt(0, row);
}
This code is used to add new header to the gridview of merged cells. After removing this code, everything works fine. But i need that code.
Export to excel code :
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Rept" + DateTime.Now.ToString("yyyy_MM_ddThh_mm_ss_") + ".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.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form);
form.Controls.Add(gvpanel);
form.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
How to solve this issue ?

I haven't find the solution anywhere, which makes me to provide this solution.
When you create a header row & also you need to export to excel, below code solves of missing the last row.
Create your dynamic header row using RowCreated Event.
protected void Grid_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridViewRow HeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell HeaderCell1 = new TableCell();
HeaderCell1.Text = "Solved your Issue";
HeaderCell1.ColumnSpan = 10;
HeaderRow.Cells.Add(HeaderCell1);
Grid.Controls[0].Controls.Add(HeaderRow);
}
}
and now you can call your ExportToExcel method:
private void ExportToExcel(GridView gv, string exportfilename)
{
string filename = exportfilename + ".xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
gv.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.Flush();
Response.End();
}

You can use an excel spreadsheet as a data source to your GridView and connect to it like any other database:
How To Query and Display Excel Data by Using ASP.NET, ADO.NET, and Visual Basic .NET

Related

Export data with images to Excel

I am exporting data with images to Excel by using the following code.
Code
protected void ExportToExcel(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = "select CustomerID, ContactName, City, PostalCode, display_picture" +
" from customers";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=DataTable.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i .textmode { mso-number-format:\#; } ";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
The Excel is downloading properly. But the problem is when I am filtering the data in the Excel. The images in the Excel are in Move but don't size with cells property. How to make the images with the property, Move and size with cells?
Your code doesn't create an Excel file at all, it creates an HTML table and sends it with a fake content type, that of the old binary Excel format (xls). Excel isn't fooled, it detects that this is an HTML table and tries to import it using default settings. This can break for any number of reasons.
It's far easier and cheaper to create a real Excel file with a library like EPPlus. For starters, you can fill a sheet directly from a DataTable  :
protected void ExportToExcel(object sender, EventArgs e)
{
///...
DataTable dt = GetData(cmd);
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
ws.Cells["A1"].LoadFromDataTable(dt, true);
//That's it!
//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());
}
}
You can add pictures with the Drawings.AddPicture method :
ExcelPicture pic = ws.Drawings.AddPicture("pic1", new FileInfo("PathToMyImage.png"));
The result is an xlsx file which is a package of compressed XML files. This means it's actually smaller than the HTML table or CSV files that are often generated instead of actual Excel files.
EasyXLS is a library that also exports xlsx and xls files with images.
//Create a workbook
ExcelDocument workbook = new ExcelDocument();
//Add a worksheet
ExcelWorksheet worksheet = new ExcelWorksheet("Gridview");
workbook.easy_addWorksheet(worksheet);
//Add the gridview to the worksheet
DataSet dataSet = new DataSet();
dataSet.Tables.Add((DataTable)GridView1.DataSource);
worksheet.easy_insertDataSet(dataSet);
//Add an image
worksheet.easy_addImage("image.jpg", "A10");
//Exporting gridview with image
workbook.easy_WriteXLSXFile("DataTable.xlsx");
More about inserting images, you can find at:
http://www.easyxls.com/manual/basics/excel-image-import-export.html
If the image bytes are loaded from database, you will need to temporary save the image locally on machine.
You can also check how to export gridview to excel to see more about formatting the data.

Cannot export to Excel in IE 11

I have a web application that exports data from a gridview to Excel. It works fine in Chrome but doesn't work in IE 11 and Firefox. I see a lot of issues with this when I google it but this error seems to be unique.
protected void ExportToExcel(List<MapAmericas.Model.Project> Projects)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.AddHeader("content-disposition", "attachment;filename=MyFile" + DateTime.Now.ToString() + ".xls");
Response.Charset = "";
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
this.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
GridView gv = new GridView();
gv.AutoGenerateColumns = false;
gv.RowDataBound += new GridViewRowEventHandler(dataExportExcel_ItemDataBound);
gv.DataSource = Projects;
gv.DataBind();
gv.RenderControl(htw);
Response.Write(AddExcelStyling()); //this contains the opening html elements
StringBuilder sbResponseString = new StringBuilder();
sbResponseString.Append(sw + "</body></html>");
Response.Write(sbResponseString.ToString());
Response.Flush();
Response.Close();
Response.End();
}
...and the issue I'm getting has to do with not being able to access Temporary Internet Files. I get a popup "Problems during Load" and about a dozen entries: "Missing File...Temporary Internet Files\Content\" and then I get a message reading "Unable to read file".
I had an image to represent the error but I'm not able to upload images.
When I click on one of the links, it loads up my webpage without any styles and I don't get an excel file.
Does anyone know what the issue would be?
I got it! I added 2 lines of code to my existing code and it works. See lines marked with **:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
//HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Panorama_Project-" + DateTime.Now.ToString() + ".xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
this.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
GridView gv = new GridView();
gv.AutoGenerateColumns = false;
gv.RowDataBound += new GridViewRowEventHandler(dataExportExcel_ItemDataBound);
gv.DataSource = Projects;
gv.DataBind();
gv.RenderControl(htw);
HttpContext.Current.Response.Write(AddExcelStyling());
StringBuilder sbResponseString = new StringBuilder();
sbResponseString.Append(sw + "</body></html>");
**HttpContext.Current.Response.AddHeader("Content-Length", sbResponseString.Length.ToString());**
HttpContext.Current.Response.Write(sbResponseString.ToString());
//HttpContext.Current.Response.Flush();
//HttpContext.Current.Response.Close();
//HttpContext.Current.Response.End();
**System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();**
It seems as though it was trying to display the entire Response object which included my page and all linked resources. The Content-Length and replacing Reponse.End and Response.Flush with System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest() seems to do the trick.
This is the simplified version of an Export To Excel function (for a datatable) that I use and one that works for all the browsers. See if this helps. The code is quite similar to yours though:
public void ExportDataToExcel(String FileName, DataTable dtData)
{
// get gridview out of datatable
GridView gv = new GridView();
gv.AllowPaging = false;
gv.DataSource = dtData;
gv.DataBind();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition",
"attachment;filename=" + FileName + ".xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < gv.Rows.Count; i++)
{
// Apply text style to each Row
gv.Rows[i].Attributes.Add("class", "textmode");
}
gv.RenderControl(hw);
HttpContext.Current.Response.Output.Write(sw.ToString());
// commenting this out to resolve this error
// System.Web.HttpException: The remote host closed the connection.
// The error code is 0x800703E3.
// HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}

Error while converting gridview with paging into excel

I am using the following code to convert gridview to ms-excel format. The problem is this if i use following code one 1st page is converted into ms-ecxel
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
string file1 = TextBox1.Text + ".xls";
string attachment = string.Format("attachment;filename={0}", file1);
this.EnableViewState = false;
Response.AddHeader("content-disposition", attachment);
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
and if add these two lines to my code i"ll get blank ms-excel sheet
GridView1.AllowPaging = false;
this.Emp_Wrklog();
please do the needful changes in my code so that i can cnvert my gridview having paging into excel. Thanks in advance.
You should definitely use EPPlus library or something like that for manipulating excel files.
http://epplus.codeplex.com/

Export data from a Gridview to Excel and save it in a folder

I am trying to export data from a Gridview to Excel and save that Excel file in a folder on the server. I have done the Excel generation part. But I am not able to save that in a folder.
Please find my code below.
Code
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "order.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gridX.AllowPaging = false;
bindX();
gridX.HeaderRow.Style.Add("background-color", "#FFFFFF");
for (int i = 0; i < gridX.HeaderRow.Cells.Count; i++)
{
gridX.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
gridX.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
Please help me to solve the issue.
Hope this will help you. First fill the gridview control then use the RenderControl() method to render grid in excel to a specific path.
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
protected void Button1_Click(object sender, EventArgs e)
{
using (StreamWriter sw = new StreamWriter("c:\\test.xls"))
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
GridView1.RenderControl(hw);
}
}
}

How to remove paging text in excel sheet while exporting data from GridView to Excelsheet?

I implemented export to excel functionality in asp.net application.Here i export data from Grid-view to excel-sheet.I also applied Paging in Grid-view.
So when i export data from Grid-view to excel sheet,paging text also display in excel sheet as shown in the given image.
How can we remove it
i follow the below approach for exporting data
Code-Behind:
Response.Clear()
Response.ClearHeaders()
Response.AddHeader("content-disposition", "attachment;filename=sample.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.xls"
Dim sb As StringBuilder = New StringBuilder()
Dim objStringWriter As StringWriter = New StringWriter(sb)
Dim objHtmlTextWriter As HtmlTextWriter = New HtmlTextWriter(objStringWriter)
//gvSample is Gridview server control
gvSample.RenderControl(objHtmlTextWriter)
Response.ContentEncoding = Encoding.Unicode
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble())
Response.Write(objStringWriter)
Response.End()
Thanks
Before rendering - disable the paging, bind the data and then render:
gvSample.AllowPaging = false;
gvSample.DataSource = ds; //Data Source
gvSample.DataBind();
gvSample.RenderControl(objHtmlTextWriter)
when ever to get the data from database for show the gridview,before that but the result content in viewstate[""] after the reuse it. when search the data for filter the main content the updated data will present in the viewstate, so you will get correct data to export
gvSample.AllowPaging = false;
gvSample.DataSource = ViewState["vsData"]; //Data Source
gvSample.DataBind();
gvSample.RenderControl(objHtmlTextWriter);
It works using SQL DataSourceID
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.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();
Response.End();
other attached asp coding file
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["ondblclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Edit$" + e.Row.RowIndex);
e.Row.Attributes["style"] = "cursor:pointer";
}
}

Resources