I have a gridview that needs to be exported to Excel. I have managed to remove the Checkboxes from Rows but don't know how to remove from the Header and also delete the Checkbox Column entirely. Thanks for help.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Id">
<Columns>
<asp:TemplateField HeaderText="Select" >
<HeaderTemplate>
<input id="chkAll" onclick="checkAll(this);" runat="server" type="checkbox" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Event" HeaderText="Event" SortExpression="Event" />
<asp:BoundField DataField="Event_Description" HeaderText="Event_Description" SortExpression="Event_Description" />
<asp:BoundField DataField="Start_Date" HeaderText="Start_Date" SortExpression="Start_Date" />
</Columns>
</asp:GridView>
Here's the backend C# code to export to excel.
protected void download_Click(object sender, EventArgs e)
{
PrepareGridViewForExport(GridView1);
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=GridViewToExcel.xls");
Response.ContentType = "application/excel";
StringWriter sWriter = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
GridView1.RenderControl(hTextWriter);
Response.Write(sWriter.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
private void PrepareGridViewForExport(Control gv)
{
Literal l = new Literal();
string name = String.Empty;
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(CheckBox))
{
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
PrepareGridViewForExport(gv.Controls[i]);
}
}
}
Try out this export function , which hides not needed column i.e column 0 of the row...
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.DataBind();
GridView1.HeaderRow.Cells[0].Visible = false;
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
GridViewRow row = GridView1.Rows[i];
row.Cells[0].Visible = false;
row.Cells[0].FindControl("chkCol0").Visible = false;
}
GridView1.RenderControl(hw);
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
}
or
On your export, drop the column. Something something like:
GridView1.Columns[0].visible = false;
GridView1.DataBind();
GridView1.RenderControl(htmlWrite);
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
Instead of hiding the control we can remove them before exporting into Excel.This can be done by looping through the cell and find the controls present in the cell. Then identify the control type and remove them from that cell.
Following is the code:
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
cell.CssClass = "textmode";
for (int i = 0; i < cell.Controls.Count; i++)
{
Control ctr = cell.Controls[i];
if (ctr is TextBox)
cell.Controls.Remove(ctr);
else if (ctr is DropDownList)
cell.Controls.Remove(ctr);
else if (ctr is Label)
{
if (ctr.ClientID.Contains("lblrow"))
cell.Controls.Remove(ctr);
}
}
}
}
In the above code I am looping through the each row and cells. Then removing all the TextBox, DropdownList and Label with the ID lblrow which are present there.
Related
I have a Gridview that I'm trying to export to a csv file, but I'm not getting any rows just column names.
<div style ="height:600px; width:auto; overflow:auto;">
<p class="padding">
<asp:GridView ID="GridViewBICARB" runat="server"
AutoGenerateColumns="false"
Caption="Bicarb Operator Checks"
CaptionAlign="Top"
EmptyDataText="Data Not Available"
Width="100%"
AllowPaging="false"
AllowSorting="true"
ShowHeader="true" >
<Columns>
<asp:BoundField DataField="FeedCheck" HeaderText="FeedCheck" />
<asp:BoundField DataField="VisualCheck" HeaderText="VisualCheck" />
</Columns>
<RowStyle CssClass="altrow" />
</asp:GridView>
</p>
</div>
This is my C#
protected void btnExportReport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=test.csv");
Response.Charset = "";
Response.ContentType = "text/csv";
GridViewBICARB.AllowSorting = false;
GridViewBICARB.AllowPaging = false;
GridViewBICARB.DataBind();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < GridViewBICARB.Columns.Count; k++)
{
//add separator
sb.Append(GridViewBICARB.Columns[k].HeaderText + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < GridViewBICARB.Rows.Count; i++)
{
for (int k = 0; k < GridViewBICARB.Columns.Count; k++)
{
//add separator
sb.Append(GridViewBICARB.Rows[i].Cells[k].Text + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
My output is just the column names.
FeedCheck,VisualCheck,
I've tried removing the following as suggested in another question.
GridViewBICARB.AllowPaging = false;
GridViewBICARB.DataBind();
But no help....
I ended up adding OnPageIndexChanging = "OnPaging"to my gridview. The PageIndexChanging event is raised when one of the pager buttons is clicked, but before the GridView control handles the paging operation. This enables you to provide an event-handling method that performs a routine.
In my case this was my routine...
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
GridViewBICARB.PageIndex = e.NewPageIndex;
GridViewBICARB.DataBind();
}
The NewPageIndex property was to determine the index of the page selected by the user in the page selection element of the DataGrid control. This value is often used to set the CurrentPageIndex property of the DataGrid control to display the selected page.
Then I removed the following...
GridViewBICARB.AllowSorting = false;
GridViewBICARB.AllowPaging = false;
GridViewBICARB.DataBind();
And wallah it works!
I'm exporting a gridview to excel sheet on a button click event but the exported excel sheet is displaying only below information
Instead of the gridview data. Below if the code inside the export button click
private void ExportGridView(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
Also the code in the aspx for gridview is
......
<asp:GridView ID="GridView1" runat="server" Font-Size="10pt" AllowSorting="True"
BackColor="White" BorderColor="#CCCCCC" AutoGenerateSelectButton="true"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowDataBound="GridView1_RowDataBound" OnSorting="GridView1_Sorting">
<%-- <Columns>
....................
<td> <asp:Button runat="server" ID="btnExport" Text="Export to Excel" onclick="btnExport_Click" /></td>
</tr>
</table>
</asp:Content>
I resolved the issue.I did not bind the gridview after settting allowpaging to false. Below is the full code:
private void ExportGridView(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
//GridView1.DataBind();
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
Also, another change was in .aspx file in the page I set EnableEventValidation = "false"
When i am trying to get excel export from my mysqldatabase, it doesnt do anything on button_click. I can see that gridview is filling by DataTable but on postback it doesnt download the excel output of my gridview.I cant find out that where is the problem. Thanks for helping guys.
Here is my .aspx gridview code
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
runat="server" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging">
<Columns>
<asp:BoundField DataField="isbn" HeaderText="isbn" ItemStyle-Width="150px" />
<asp:BoundField DataField="display_name" HeaderText="bookName" ItemStyle-Width="100px" />
<asp:BoundField DataField="authorName" HeaderText="authorName" ItemStyle-Width="100px" />
</Columns>
Here is my databind and button click
private void BindGrid()
{
DataTable dt = book.getAllbookExcelExport();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnExport_ServerClick(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
this.BindGrid();
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 { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
Here is my page_load
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(btnSave);
if (!Page.IsPostBack)
{
this.BindGrid();
}
}
I am working on a ASP.NET 4.5 Webform and I have a Gridview (that has custom TemplateField and gets data from a sqlDataSource)
I have this event to export the gridview contents to an excel sheet, and it does its jobs well except the created file is giving out an warning when user open it (which I understand because the file that got created is not an actual excel file):
"the file you are trying to open is in a different format than
specified by the file extension"
protected void btnExport_Excel_Click(object sender, EventArgs e)
{
try
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GV.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
//Response.ContentType = "application/text";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView4.AllowPaging = false;
GridView4.AllowSorting = false;
GridView4.ShowFooter = false;
GridView4.DataBind();
//this.BindGrid();
GridView4.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView4.HeaderRow.Cells)
{
cell.BackColor = GridView4.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView4.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView4.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView4.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView4.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
//Display message
InfoPanel.Visible = true;
InfoPanel.CssClass = "panel panel-success";
lblMessage.CssClass = "text text-sucess bold";
lblMessage.Text = "File has been exported!";
}
catch (Exception ex)
{
//Display message
InfoPanel.Visible = true;
lblMessage.Text = "<b>An error has occurred. Please try again later!</b></br>" + ex.Message;
lblMessage.CssClass = "text text-danger bold";
InfoPanel.CssClass = "panel panel-danger";
panelResult.Visible = false;
}
}
the result in the Excel .xls file is good (no styles except header columns, no footer, just exact as shown on the Gridview):
I am finding another way to avoid this warning, so I see people like to use
ClosedXML, so I replace that event above with this event:
protected void ExportExcel(object sender, EventArgs e)
{
DataTable dt = new DataTable("GridView_Data");
foreach(TableCell cell in GridView4.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (GridViewRow row in GridView4.Rows)
{
dt.Rows.Add();
for (int i=0; i<row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;
}
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GV.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
and the result is bad (only good new is that the exported file is a real 2007+ Excel sheet so no warnings):
How do I get the "good" result above using closedXML?
The main problem in you second part of code (with ClosedXML) , that you are trying to use Text property of GridViewRow for TemplateField field columns. As you can see here, you can get field value via Text property only for BoundField field columns and automatically generated field columns.
To get value from TemplateField you should navigate to inner control which contains value and get value from it.
If you have the following column template:
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="labelName" runat="server" Text ='<%# Eval("ABC")%>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Your code should be:
for (int i=0; i<row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = (row.Cells[i].FindControl("labelName") as Label).Text;
}
EDIT
Your code should be as follows:
protected void ExportExcel(object sender, EventArgs e)
{
DataTable dt = new DataTable("GridView_Data");
foreach (DataControlField col in GridView4.Columns)
{
dt.Columns.Add(col.HeaderText);
}
foreach (GridViewRow row in GridView4.Rows)
{
dt.Rows.Add();
for (int i = 0; i < row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = (FindControl(row.Cells[i].Controls, "lbl") as Label).Text;
}
}
//your code below is not changed
}
protected Control FindControl(ControlCollection collection, string id)
{
foreach (Control ctrl in collection)
{
if (ctrl.ID == id)
return ctrl;
}
return null;
}
Ensure that all Label controls used in TemplateField have the same ID as "lbl":
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text ='<%# Eval("ID")%>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text ='<%# Eval("Name")%>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text ='<%# Eval("Amount")%>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
I tried it's working ,please find the code hope it will help you:
Index.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="ExportExcel.Index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle- ForeColor="White"
runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#Eval("Name") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" Text='<%# Eval("Country") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnExport" Text="Export" runat="server" OnClick="btnExport_Click" />
</div>
</form>
Index.aspx.cs
using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ExportExcel
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
GetData();
}
}
private void GetData()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Country", typeof(string)) });
dt.Rows.Add(1, "abc", "UK");
dt.Rows.Add(2, "def", "India");
dt.Rows.Add(3, "ghi", "France");
dt.Rows.Add(4, "jkl", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnExport_Click(object sender, EventArgs e)
{
try
{
DataTable dt = new DataTable("GridView_Data");
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (GridViewRow row in GridView1.Rows)
{
TextBox txtNameRow = (TextBox)row.FindControl("txtName");
Label lblCountryRow = (Label)row.FindControl("lblCountry");
DataRow drow = dt.NewRow();
for (int i = 0; i < GridView1.Columns.Count; i++)
{
drow[i] = row.Cells[i].Text;
}
drow["Name"] = txtNameRow.Text;
drow["Country"] = lblCountryRow.Text;
dt.Rows.Add(drow);
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GV.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
catch (Exception ex)
{
throw;
}
}
}
}
I call the Export to Excel on a button click event like the following
protected void btnPrint_Click(object sender, EventArgs e)
{
fileName = string.Format(fileName, DateTime.Now.ToString("MMddyyyy_hhmmss"));
Extensions.ExportToXcel_SomeReport(dt, fileName, this.Page);
}
from there I have a utils class called Extensions where I have the ExportToExcel_SomeReport method defined
public static class Extensions
{
internal static void ExportToXcel_SomeReport(DataTable dt, string fileName, Page page)
{
var recCount = dt.Rows.Count;
RemoveHtmlSpecialChars(dt);
fileName = string.Format(fileName, DateTime.Now.ToString("MMddyyyy_hhmmss"));
var xlsx = new XLWorkbook();
var ws = xlsx.Worksheets.Add("Some Report Name");
ws.Style.Font.Bold = true;
ws.Cell("C5").Value = "YOUR REPORT NAME";
ws.Cell("C5").Style.Font.FontColor = XLColor.Black;
ws.Cell("C5").Style.Font.SetFontSize(16.0);
ws.Cell("E5").Value = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
ws.Range("C5:E5").Style.Font.SetFontSize(16.0);
ws.Cell("A7").Value = string.Format("{0} Records", recCount);
ws.Style.Font.Bold = false;
ws.Cell(9, 1).InsertTable(dt.AsEnumerable());
ws.Row(9).InsertRowsBelow(1);
// ws.Style.Font.FontColor = XLColor.Gray;
ws.Columns("1-9").AdjustToContents();
ws.Tables.Table(0).ShowAutoFilter = true;
ws.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
DynaGenExcelFile(fileName, page, xlsx);
}
/// <summary>
/// Remove all HTML special characters from datatable field if they are present
/// </summary>
/// <param name="dt"></param>
private static void RemoveHtmlSpecialChars(DataTable dt)
{
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
dt.Rows[rows][column] = dt.Rows[rows][column].ToString().Replace(" ", string.Empty);
}
}
}
/// <summary>
/// Call this Method to Generate the Excel Files from different Lap Reports depending on which one has been selected
/// </summary>
/// <param name="fileName"></param>
/// <param name="page"></param>
/// <param name="xlsx"></param>
private static void DynaGenExcelFile(string fileName, Page page, XLWorkbook xlsx)
{
page.Response.ClearContent();
page.Response.ClearHeaders();
page.Response.ContentType = "application/vnd.ms-excel";
page.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.xlsx", fileName));
using (MemoryStream memoryStream = new MemoryStream())
{
xlsx.SaveAs(memoryStream);
memoryStream.WriteTo(page.Response.OutputStream);
}
page.Response.Flush();
page.Response.End();
}
}
Contrary to popular belief, you can set the extension of your file to be .html, and Excel can open it up.
Just set the extension to HTML:
Response.AddHeader("content-disposition", "attachment;filename=GV.html");
And retain Excel as the content type:
Response.ContentType = "application/ms-excel";
EDIT: Oh, right, forgot to mention, this should make that annoying dialog go away.
EDIT 2: Looks like the original question has changed... now it's talking about using ClosedXML... but I'll leave this answer here just in case someone else is using HTML and Excel.
I have tried code for saving entire gridview data to an excel file and it is working fine but now i want to save only particular columns of gridview to an excel file.I have used mysql database and asp.net with C#.Please anyone help me with this.
**default.aspx**
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<asp:Button ID="btnSave" runat="server" Text="Save to Excel" OnClick="btnSave_Click" />
**default.cs**
protected void btnSave_Click(object sender, EventArgs e)
{
ExportGridToExcel(GridView1, "StudentMarks.xls");
}
public void ExportGridToExcel(GridView grdGridView, string fileName)
{
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
grdGridView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
return;
}
To generate excel use this method ..
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition","attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView.AllowPaging = false;
// Re-Bind data to GridView
using (MSEntities1 CompObj = new MSEntities1())
{
// code for bind grid view
GridView.DataBind();
}
// Change the Header Row back to white color
GridViewC.Style.Add(" font-size", "10px");
GridView.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Apply style to Individual Cells
GridView.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[3].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[4].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[5].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[6].Style.Add("background-color", "green");
GridView.HeaderRow.Cells[7].Style.Add("background-color", "green");
int k = GridView.Rows.Count;
for (int i = 1; i < GridView.Rows.Count; i++)
{
GridViewRow row = GridView.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
row.Cells[3].Style.Add("background-color", "#C2D69B");
row.Cells[4].Style.Add("background-color", "#C2D69B");
row.Cells[5].Style.Add("background-color", "#C2D69B");
row.Cells[6].Style.Add("background-color", "#C2D69B");
row.Cells[7].Style.Add("background-color", "#C2D69B");
}
}
GridView.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();
}
You can use asp:boundfield to select the columns which you want to display in the gridview. Then export that gridview to excel.
Ok.In your case you can bind a new gridview with same data but without Edit/Delete column. You can set the visibility of this new gridview to false.