In this article, I’m describing ,how to export data from grid view to excel and Csv using ASP.NET and C#.Recently I’m working on a project in which I got a task, we need to export Grid View records to Excel sheet with an instruction. I need to focus on Excel sheet formatting while exporting records to Excel sheet.
we need to export GridView header name, row background color also. I have completed my task successfully Now I decided to share my experience with other developers who are looking for the same.
For explanation, I have also created a “Users” table in the database.
SQL Create Script
CREATE TABLE [dbo].[Users](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[Email] [nvarchar](max) NOT NULL,
[Password] [nvarchar](max) NULL,
[About] [nvarchar](max) NULL,
[DOB] [datetime2](7) NULL,
[Gender] [int] NOT NULL,
[Location] [nvarchar](max) NULL,
[ContactNo] [nvarchar](max) NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
- So let’s start and add an empty website.
- Add a Webform page in the project and copy-paste below code
In my Web page, I have two button controls to export the data to excel and Csv. Onclick of that Button we are going to export the Gridview data to excel sheet or Csv File.
Aspx Code:
<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="GridView" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="btnexportexcel" runat="server" Text="Export To Excel" OnClick="btnexportexcel_Click" />
<asp:Button ID="btnExcportcsv" runat="server" Text="Export To Csv" OnClick="btnExcportcsv_Click" />
<br />
<br />
<asp:GridView ID="UserDataGrid" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" OnPageIndexChanging="GridView1_PageIndexChanging" Width="264px">
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</form>
</body>
</html>
Code Behind
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class GridView : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=ADEQUATE-ASHOK\\SQLEXPRESS01;Initial Catalog=DemoDataBase;User ID=adk;Password=adk@1234");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
public void BindGrid()
{
UserDataGrid.DataSource = GetDataSet();
UserDataGrid.DataBind();
}
public DataSet GetDataSet()
{
SqlCommand cmd = new SqlCommand("select * from Users", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
UserDataGrid.DataSource = GetDataSet();
UserDataGrid.PageIndex = e.NewPageIndex;
UserDataGrid.DataBind();
}
protected void btnexportexcel_Click(object sender, EventArgs e)
{
ExportGridToExcel();
}
protected void btnExcportcsv_Click(object sender, EventArgs e)
{
ExportGridToCsv();
}
public void ExportGridToExcel()
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=ExportUserData.xls");
Response.ContentType = "File/Data.xls";
StringWriter StringWriter = new System.IO.StringWriter();
HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);
UserDataGrid.RenderControl(HtmlTextWriter);
Response.Write(StringWriter.ToString());
Response.End();
}
public void ExportGridToCsv()
{
// set the resulting file attachment name to the name of the report...
string fileName = "test";
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".csv");
Response.Charset = "";
Response.ContentType = "application/text";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
// Get the header row text form the sortable columns
LinkButton headerLink = new LinkButton();
string headerText = string.Empty;
for (int k = 0; k < UserDataGrid.HeaderRow.Cells.Count; k++)
{
//add separator
headerText = UserDataGrid.HeaderRow.Cells[k].Text;
sb.Append(headerText + ",");
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < UserDataGrid.Rows.Count; i++)
{
for (int k = 0; k < UserDataGrid.HeaderRow.Cells.Count; k++)
{
//add separator and strip "," values from returned content...
sb.Append(UserDataGrid.Rows[i].Cells[k].Text.Replace(",", "") + ",");
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/*we are calling GridView1.RenderControl(htmlTextWriter) for exporting the data,
* hence you will an exception that a Server-Control was rendered outside of a Form.*/
/*To avoid this exception this peace of code Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
}
You can notice in the code I made two changes for avoiding below error.
<%@ Page ............ EnableEventValidation="false" %>
public override void VerifyRenderingInServerForm(Control control)
{
}
If you want to give custom style and color to your excel sheet then use the below code.
Export gridview to excel with custom value formatting and color
public void CustomExcelStyleExport()
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "ExportUserData.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
UserDataGrid.AllowPaging = false;
UserDataGrid.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < UserDataGrid.HeaderRow.Cells.Count; i++)
{
UserDataGrid.HeaderRow.Cells[i].Style.Add("background-color", "#009688");
}
int j = 1;
//Set alternate row color
foreach (GridViewRow gvrow in UserDataGrid.Rows)
{
gvrow.BackColor = System.Drawing.Color.White;
if (j <= UserDataGrid.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
UserDataGrid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
The post Export Gridview to Excel and Csv in Asp .Net With Formatting Using c# appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- gRPC and ASP Net Core: using SslCredentials with non-null arguments is not supported by GrpcChannel
- Select2 with ASP dropdownlist control using ajax and paging
- Using C# to populate a DataGridView with CSV file, and update Access database with results
- Export to Excel in ASP.NET, issue with decimal formatting for numbers greater than 1000
- Problem with export date to csv file, how to export date to excel
- ASP NET Core MVC delete row and local file at the same time using Url.Action in <a>
- Deflate with Pako and inflate with asp net core
- How to find next blank row and export form data to excel using C#
- How to preserve decimal precision when exporting to a csv and opened with excel
- asp gridview with checkbox and select
- Export to Excel using OpenXML and C#, Integers and DateTime
- Save Excel Worksheet as CSV with null and semicolon as separator
- upload excel file using ASP.net and C#
- Problem with building and using Scintilla.NET
- Pass Method ( of void return type and with no input arguments) as parameter using C#
- export Datagrid to excel asp
- How to enter data with leading zero into the excel using c# excel application
- Issue when using only a getter and issue with List in c#
- Freeing connections and commands with using
- Export DataTable to CSV File with "|" Delimiter
- Using Excel 2013 with C# incorrect row numbers
- Programmatically export query table from MS Access to Excel using C#
- A Simple Photo Album with Pinch and Zoom using FlipView
- Changing Excel cell properties with C# using Late Binding
- Using friction with XNA and C#
- Parse text with date and timestamp using Regex in C#
- Using arrays and pointers in C# with C DLL
- How to create Excel 2003 UDF with a C# Excel add-in using VSTO 2005 SE
- How to work with a main project and sub-projects in visual studio using namespace
- How to interact with Excel files using C# ASP.NET
- Type to track the position of a list using IEnumerable
- Find all class names in a WPF project
- How to merge gridview rows
- Show alert message before redirecting to other page ASP.NET
- REGEX matches in tester but not C#
- OData V4 property access
- does HttpWebRequest send certificate's Private Key over internet?
- What is DateTime.ToBinary vs. Ticks and FromBinary vs. constructor
- Cannot Implicitly Convert Type in XNA
- C# join dictionaries, with additional information
- Storing a list of strings and arrays
- Unity Navmesh Performance Issue
- WCF 4 service responds to localhost address but not machine name
- Create constant size Background Image in Wrap Panel in WPF
- C# Npgsql, Call of procedure supported ?
- How to fix "Compression JPEG is only supported with a single strip" issue
- Creative ways to converting a Collection of objects to a javascript array in c#
- Data structure for storing keywords and synonyms in C#?
- My first game in XNA(Little problem)
- WPF + Binding DataGrid ItemSource to List