Exporting GridView data to Excel,Word, & Text file is a very common task which is performed in most of the asp.net web applications to meet the customized reporting purposes. There are various techniques of exporting the GridView to excel and it highly depends on the application scenario. I will show you that how you can export your GridView data to Excel file, Word file and also Text file. When exporting keep the format of data is a very frequent requirement and also user might want to set different format which i will discuss in the later section of this post. So lets start with direct export to excel. Atfirst we need to create a table in sql server database. Table looks like:
Now we need to add a page. Add a GridView, Button in our page to export data. Now page design is completed. So now we need to bind data to the GridView first. Write the below code under Page_Load event to read data from sql server table:
Export to Excel when GridView has paging: Its a little bit tricky to export data when GridView has Paging functionality. Just set the AllowPaging property to False beforeexporting data. Now export button click event code like:
Export to Excel when GridView contains control: Replace corresponding GridView cells by controls value. Let you have a supplier list & you wantto display each supplier location as well as you want a facility that when user open thelist then user can see the regions other suppliers in a popup. To do that you have to add a link button in your GridView so that user can click on the link to view the other suppliers. Alsoyou have to export region value to Excel file. So how you can handle. Answer is replace the cell valueby link text just before exporting. Code sample:
//Read each GridView Row Data by itearation & replace foreach (GridViewRow oItem in gvEdit.Rows) { LinkButton lnk=((LinkButton)oItem.FindControl("lnk")); oItem.Cells[4].Text=lnk.Text; lnk.Visible = false; // Remove other controls like radio,dropdown or html controls also in the above way } Response.Clear(); Response.AddHeader("content-disposition", "attachment; filename=SupplierList.xls"); Response.ContentType = "application/vnd.xls"; System.IO.StringWriter WriteItem = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlText = newHtmlTextWriter(WriteItem); gvEdit.RenderControl(htmlText); Response.Write(WriteItem.ToString()); Response.End();
Output sample:
Export to Word: To export GridView data to ms-word just modify your button click event by the following code sample:
Export to Text: To export GridView data to a text file just modify your button click event by the following code sample:
//Always use StringBuilder for string operations it will enhance the performence System.Text.StringBuilder str = new System.Text.StringBuilder(); foreach (GridViewRow oItem in gvEdit.Rows) { for (int j = 0; j <= oItem.Cells.Count- 1; j++) str.Append(oItem.Cells[j].Text+" "); str.Append("\r\n"); } Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=SupplierList.txt"); Response.ContentType = "application/vnd.text"; Response.Write(str.ToString()); Response.End();
Export to Excel with proper fomatting: Hope from above example now one can easily export data from GridView. But an important concern is to setthe formatting to the target file. In this reagard mso-number-format ease our life. Lets we need todisplay date & time in the GridView but we wants short date format when exporting. To do the one can use mso-number-format in the following way. Modify your export button click event by the following code segment.
Note: If you do not find your required format from above list then try creating a spreadsheet with a single cell entry according to your required format. Then from file menu select the 'Save as Web Page' option to create a html file. Read & examine the code for this and findout the mso-number-format from the style declarations.
(selectisnull(sum(amount),0)from usercommission where UserId = Main.UserId and UserLevel =1 and Commissiondate betweencoalesce(@FromDate,Commissiondate)andcoalesce(@ToDate+1,Commissiondate))as CommissionLevel1 ,
(selectisnull(sum(amount),0)from usercommission where UserId = Main.UserId and UserLevel =2 and Commissiondate betweencoalesce(@FromDate,Commissiondate)andcoalesce(@ToDate+1,Commissiondate))as CommissionLevel2 ,
(selectisnull(sum(amount),0)from usercommission where UserId = Main.UserId and UserLevel =3 and Commissiondate betweencoalesce(@FromDate,Commissiondate)andcoalesce(@ToDate+1,Commissiondate))as CommissionLevel3 ,
(selectisnull(sum(amount),0)from usercommission where UserId = Main.UserId and UserLevel =4 and Commissiondate betweencoalesce(@FromDate,Commissiondate)andcoalesce(@ToDate+1,Commissiondate))as CommissionLevel4 ,
(selectisnull(sum(amount),0)from usercommission where UserId = Main.UserId and UserLevel =5 and Commissiondate betweencoalesce(@FromDate,Commissiondate)andcoalesce(@ToDate+1,Commissiondate))as CommissionLevel5 ,
(selectisnull(sum(amount),0)from usercommission where UserId = Main.UserId and UserLevel =6 and Commissiondate betweencoalesce(@FromDate,Commissiondate)andcoalesce(@ToDate+1,Commissiondate))as CommissionLevel6
from UserInfo Main
where Main.UserID=Coalesce(@UserId,Main.UserId)and Main.UserType=coalesce(@UserType,Main.UserType)
INSERTINTO @EdvStatus (UserId,EdvExpiryDate,Status)(select UserId,EdvExpiryDate,Status from EdvStatus);
selectdistinctCurES.UserId,U.UserName,U.UserType,LK.LookupValue As UserTypeName,(selectcount(Status)from @EdvStatus where UserId=CurES.UserId)as SendEDV,
(selectcount(Status)from @EdvStatus where Status='Used'and UserId=CurES.UserId)as EnrolledEDV,
(selectcount(Status)from @EdvStatus where Status='Expired'and UserId=CurES.UserId)as ExpiredEDV,
(selectcount(Status)from @EdvStatus where Status='Active'and UserId=CurES.UserId)as RemainEDV ,
(selectsum(Amount)from UserCommission where UserCommission.UserId=CurES.UserId)as Commission
from @EdvStatus CurES LEFTOUTERJOIN
UserInfo U ON U.UserId=CurES.UserId LEFTOUTERJOIN
sys_Lookup LK on LK.LookupId=U.UserType
where U.UserType in(coalesce(@UserType,UserType))and U.UserType between 14 and 15
--SELECT @NewBatchNumber=('SC'+ cast(YEAR(GETDATE()) as nvarchar(4)) + cast(MONTH(GETDATE()) as nvarchar(2)) + cast((SELECT isnull(MAX(BatchId),0)+1 FROM BatchMaster) as nvarchar(15)))
WITH ParentCommissions(UserId, UserName,UserType,UserTypeName,ParentId,Levels,Commission)
AS
(
SELECT UI.UserId, UI.UserName,UI.UserType,lk.LookUpValue as UserTypeName,(select EM.UserId from EdvMaster EM where EM.EdvmasterId=UI.EdvmasterId and UI.EdvMasterId>0)as ParentId,0 as Levels,cast(0 asnvarchar(64))as Commission
FROM UserInfo UI join
sys_lookup lk On lk.LookUpId=UI.UserType
WHERE UI.UserId = @RegisterUserId
UNIONALL
SELECT U.UserId, U.UserName,U.UserType,lkp.LookUpValue as UserTypeName,(select EM.UserId from EdvMaster EM where EM.EdvmasterId=U.EdvMasterId)as ParentId,UComm.Levels+1as Levels,
(casewhen lkp.LookUpValue='PP'then
(Select [Value] from sys_Parameters where [key]='PPCommissionLevel'+rtrim(cast((UComm.Levels+1)aschar(5))))
when lkp.LookUpValue='SPP'then
(Select [Value] from sys_Parameters where [key]='SPPCommissionLevel'+rtrim(cast((UComm.Levels+1)aschar(5))))
when lkp.LookUpValue='WebUser'then
(select [value] from sys_parameters where [key]='NormalCommissionLevel'+rtrim(cast((UComm.Levels+1)aschar(5))))
end)as Commission
FROM UserInfo AS U JOIN
sys_lookup lkp On lkp.LookUpId=U.UserType join
ParentCommissions AS UComm ON U.UserId = UComm.ParentId and UComm.Levels < 6 and U.UserId <> @RegisterUserId