How to export gridview data in excelexport data of gridview in excel?

dear friends

i m using gridview with paging facility.

can anyone tell me how do i export my gridview in excel?

its urgent.

thanks

shweta


Thanks

shweta

In a day when don't come across any problem -you can be sure that you are traveling in wrong path
0
shweta
10/23/2008 10:44:34 AM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

13 Replies
1059 Views

Similar Articles

[PageSpeed] 6

Hi please follow the link.

http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html


Valentine Day Special Song

ASP.NET ListView Control
0
sharpeffect
10/23/2008 10:56:25 AM

hi

thanks for d reply but the blog doesnt get open.

 


Thanks

shweta

In a day when don't come across any problem -you can be sure that you are traveling in wrong path
0
shweta
10/23/2008 11:21:22 AM

It is opening at my side. Here is the link.

Download the zip file from here.

Hope this will work.


Valentine Day Special Song

ASP.NET ListView Control
0
sharpeffect
10/23/2008 11:31:33 AM

ok yea that works, but it exports the table as is with the edit button, paging, and sorted headers, how would i just have it were that the content get export not everything this is my code.

Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click

GridView1.DataSource = "datasourcePullInst"

'GridView1.DataBind()

Response.Clear()

Response.Buffer = True

Response.AddHeader("Content-Disposition", "attachment; filename=Pathways.xls")

GridView1.AllowPaging = "false"

GridView1.PageSize = "100"

 

Response.ContentType = "application/vnd.ms-excel"

Dim writer As New System.IO.StringWriter()Dim html As New System.Web.UI.HtmlTextWriter(writer)

GridView1.RenderControl(html)

Response.Write(writer)

Response.End()

End Sub

Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)

 

End Sub


Thank You in advance
0
MicahG
10/23/2008 2:46:43 PM

 try this. i have this in my app_code folder in my main class common.vb

  'exports any gridview to excel document
    Public Shared Sub Export(ByVal fileName As String, ByVal gv As GridView)
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
        HttpContext.Current.Response.ContentType = "application/ms-excel"
        Dim sw As StringWriter = New StringWriter
        Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
        '  Create a form to contain the grid
        Dim table As Table = New Table
        gv.GridLines = GridLines.Both
        table.GridLines = gv.GridLines
        '  add the header row to the table
        If (Not (gv.HeaderRow) Is Nothing) Then
            common.PrepareControlForExport(gv.HeaderRow)
            table.Rows.Add(gv.HeaderRow)
        End If
        '  add each of the data rows to the table
        For Each row As GridViewRow In gv.Rows
            common.PrepareControlForExport(row)
            table.Rows.Add(row)
        Next
        '  add the footer row to the table
        If (Not (gv.FooterRow) Is Nothing) Then
            common.PrepareControlForExport(gv.FooterRow)
            table.Rows.Add(gv.FooterRow)
        End If
        '  render the table into the htmlwriter
        table.RenderControl(htw)
        '  render the htmlwriter into the response
        HttpContext.Current.Response.Write(sw.ToString)
        HttpContext.Current.Response.End()
    End Sub

    ' Replace any of the contained controls with literals
    Private Shared Sub PrepareControlForExport(ByVal control As Control)
        Dim i As Integer = 0
        Do While (i < control.Controls.Count)
            Dim current As Control = control.Controls(i)
            If (TypeOf current Is LinkButton) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text))
            ElseIf (TypeOf current Is ImageButton) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText))
            ElseIf (TypeOf current Is HyperLink) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text))
            ElseIf (TypeOf current Is DropDownList) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text))
            ElseIf (TypeOf current Is CheckBox) Then
                control.Controls.Remove(current)
                control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked))
                'TODO: Warning!!!, inline IF is not supported ?
            End If
            If current.HasControls Then
                common.PrepareControlForExport(current)
            End If
            i = (i + 1)
        Loop
    End Sub

 

and this is what i have in my pages when i want to export on my export button event

 common.Export("spreadsheet_title.xls", gridViewID)

 

please mark as answer if this helps

 

 

0
neilhanvey
10/23/2008 3:26:08 PM

 

hi

 

please see this link

http://forums.asp.net/t/1221467.aspx

 

hope this helps

Thanks

0
sharmilasubbiah
10/23/2008 3:45:30 PM

 

thanks alot u 2
Thank You in advance
0
MicahG
10/23/2008 3:48:54 PM

hi raheel

i tried your code but i get the error on

HttpContext.Current.Response.End();

the error is

'unable to evaluate an expression because the code is optimized or a native frame is on the top of the call stack'


Thanks

shweta

In a day when don't come across any problem -you can be sure that you are traveling in wrong path
0
shweta
10/24/2008 5:06:10 AM

 Hi,

Sorry for the late reply Please use the export library from codeproject. Click here.


Valentine Day Special Song

ASP.NET ListView Control
0
sharpeffect
10/24/2008 5:12:31 AM

hi raheel

i tried this one too i m sending u my code

protected void btnexport_Click(object sender, EventArgs e)

{

try

{

// DB.Export("Customers.xls", this.gvactivitylog);

 

// Get the datatable to export

DataTable dt = (DataTable)Session["dt"];

int[] iColumns = { 1, 2, 5, 7 };

string[] sHeaders = { "dateof", "act", "result", "formName"};

// Export the details of specified columns with specified headers to CSV

RKLib.ExportData.Export objExport = new RKLib.ExportData.Export();objExport.ExportDetails(dt, iColumns, sHeaders, Export.ExportFormat.CSV, "EmployeesInfo3");

 

}

catch (Exception ee)

{

throw ee;

}

finally

{

obj.Connectionclose();

}

}

but i got an error

sys.webforms.pagerequestparsererrrorexception:the message received from server could not be parsed.common causes for this error are when the response is modified by calls to response.write(),response filters, httpmodules, or server trace is enabled.

details: error parsing near "date","ac"

do u know anything abt this? 


Thanks

shweta

In a day when don't come across any problem -you can be sure that you are traveling in wrong path
0
shweta
10/24/2008 6:01:39 AM

 Hello this is not an issue because of this code. It is because of Updatepanel, which you are probably using. Please check this link.

 


Valentine Day Special Song

ASP.NET ListView Control
0
sharpeffect
10/24/2008 7:36:48 AM

thanks raheel

i wil try

 

 


Thanks

shweta

In a day when don't come across any problem -you can be sure that you are traveling in wrong path
0
shweta
10/24/2008 7:50:08 AM

 You are welcome. Try to run that code from outside the update panel. and please don't forget to "Mark As Answer" if my post help you.


Valentine Day Special Song

ASP.NET ListView Control
0
sharpeffect
10/24/2008 7:58:37 AM
Reply:

Similar Artilces:

i have work on gridview control.in that i have 3columns.name as subject,bookname,link. in this some link column data are very large.according to that data(no spaces in that data)gridview has changed.i
hi,i have work on gridview control.in that i have 3columns.name as subject,bookname,link. in this some link column data are very large.according to that data(no spaces in that data)gridview has changed.i want display half of the data and remaining display like this.(ex:http://ww.yahoo.com...........).how can i display like this,and one more thing is always the column size will constant. Try something like this: <asp:templatefield headertext="Link"> <itemtemplate> <asp:hyperlink id="HyperLink1" runat="server" navigateurl='<...

Control the language encoding for a data exported from gridview to Excel
Hello there, could anybody help me in this problem, I have a data that export to Excel but when it is exported any text that not in english will appear as rubbish.   please help me Hi:   Please open the exported file with notepad, what can you see in the <td>s? Please make sure these fields is Unicode encoding. Also try System.Web.HttpUtility.HtmlEncode(Eval("field_name")) instead of Eval("field_name") RegardsSincerely,Allen ChenMicrosoft Online Community SupportPlease remember to mark the replies as answers if they help and unmark them i...

Error Exporting Gridview data to excel Only when Gridview has template columns...[looking for work around]
Hello I have been exporting data to excel from a gridview using this code:   Protected Sub btnExportar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportar.Click ExportToExcel(sender, e) End Sub Sub ExportToExcel(ByVal Source As Object, ByVal E As EventArgs) If Me.gvDesembolsos.Rows.Count.ToString + 1 < 65536 Then Me.gvDesembolsos.Enabled = False 'gvDesembolsos.Columns(1).Visible = False 'gvDesembolsos.Columns(7).Visible = False 'gvDesembolsos.Columns(9...

Sincronize GridView data with export data
I fill a gridview with 3 different queries, depending on a level stored in a textbox named tx_nivel (nivel means level in spanish). When the level is 1, the gridview shows to the data region by region (each row shows the data of a region).If you click the row of region XYZ, the gridview shows to the data of region XYZ division by division (level 2)If you click the row of divison ABC, the gridview shows to the data of divison ABC department by department (level 3) The page also has a button to export the gridview to excel.  Note that when you are seeing the data of level 1, th...

Data presentation control in another Data presentation control
 Hello,I want to make a menu with datalist or gridview control.Basically,the menu will be like this,Categories     Sub Categories.For example, for COMPUTING category there will be NOTEBOOKS DESKTOPS etc.There will be a image for CATEGORIES and linkbuttons with Subcategories.If I put a datalist inside a datalist and a link button inside the second datalist visually it satisfies my need.However,CommandArguments come from database to linkbutton.Andwhen one of these command buttons is cliked it must go to proper page.I dont know how to wrie an event_handler ,specifically, for...

to fetch data gridview data into a data table
Hi I have one gridview. which have some textboxes and some are data boud columns. I want to fetch whole the data in the gridview into one data set or datatable.And then insert that dataset or datatable into one other database table. Is there any way to do that. Please reply as soon as possible at max_ashu@yahoo.com and ashish.gautam@rbs.com  regards Ashish Gautam Hi, >>"...and some are data boud columns..."  Where does the original data on the GridView come from? From you words, seems that it also from a DataSet? If so, you can save the input values ...

Detailed data about GridView and other Data presentation tools!
HiDoes anyone have a link or article that talks about the Gridview and other data presentation tools in-depth, by which I mean providing more data than merely Gridview.DataBind, .Source...etc. I need to learn more about these controls apart from conventional programming techniques.Thanks Karthik MuthuswamyProgrammer AnalystChennai In the Data Tutorials section of this site, they are all explained. ThanksMark post(s) as "Answer" that helped youElectronic ScrewWebsite||Blog||Dub@i.net Thanks a lot for that link. Will make the best use of it!!!Karthik MuthuswamyProgrammer An...

How do I use data gridview or any such control for data entry?
I need to bulk enter the data in a grid-view like control (i am not sure about grid view ) in which the first column is data bound from a table , second column should have a check box , then the next two columns should have text boxes and and the last column should have drop down box. on clicking the submit button, for every row that has check box checked should be added to another table.   http://www.asp.net/learn/data-access/tutorial-66-cs.aspxIf this solves your problem please mark as answer ...

Exporting Gridview data to Excel
Hi there, I am developing an application that imports an excel spreadsheet, present it in a gridview and then it should export to an existing template with different column names. The importing code works perfect. My code for exporting the gridview data is provided below and it can only create a new excel spreadsheet and save the data in the same format.  I considered doing this with advanced excel functionality, but i also reckon that the web app can be even more useful and consistant for this situation.  What i request is code the will export the gridview data to an exist...

Export Gridview data to Excel
Ive searched around the internet for this answer and found some but i would really like to learn the process of exporting the data from a gridview to excel. As in what libraries i need etc etc and why. From what i understand i need to 1. Verify Excel is on the PC, if not advise the user.2. If Excel is on the PC then the page being viewed (with the gridview) is exported and displayed in excel. The data is being retrieved from SQL database. So can anyone guide me what to do or refer me to a site so i can understand this? targetting Visual Basic .Net 2008 with ASP .Net Thanks in advance. ...

Exporting Data from a Gridview to Excel
I know this is a common topic and I really have done my homework but I've spent hours on this and can't get it to work. When I click a button and run the sub below, I'm getting the error message "RegisterForEventValidation can only be called during Render" When I try and add <%@ Page Language="VB" EnableEventValidation="false" MasterPageFile="~masterurl/default.master" %> to the page directive, I get the error message "Parser Error Message: The enableeventvalidation attribute on the page directive is not allowed in this page....

display a gridview's data as it is in another gridview data
Hi all, Following is my requirement  I have 2 pages..in one page i have placed the gridview control and binding in following way I am binding using Dataset to gridviewGridview1.DataSource = ds.Tables["Data"]; Gridview1.DataBind(); Now in the 2nd page..i need to display as it is data present in gridview of the first page but my gridview in the 2nd page will be like Gridview myGrid=new Gridview(); For this grid i need to show the data of gridview present in 1st page... I don't want to keep the dataset in session and pass it to next page and bind it overthere.....

export gridview data to excel
Can anybody help me out on how to export gridview data to excel? i'll be using it as a generatedreport in my asp.net application Two sample codes to do it >> http://codeproject.com/aspnet/DAtaGridExportToExcel.asphttp://www.c-sharpcorner.com/Code/2002/June/GridViewIV.asp  Regards, Narayana Rao Surapaneni Architect | Author | MCSD for .NET | MCSD | SCJP www.msdeveloper.info ...

Exporting Gridview data to excel
Can someone tell me what I am missing.   I am trying to export the data from a Gridview into Excel .   I am not getting any errors when doing so but no data is showing up in excel when you click open or save. Any help would be much appricated. T Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If IsPostBack Then GridView1.DataBind() End If End Sub Protected Sub bSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles bSubmit.Click Dim myConnection As SqlConnection Dim myCommand As SqlDataAda...