.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Gridview to Excel - sample

Posted By:      Posted Date: October 14, 2010    Points: 0   Category :ASP.Net


I am trying to work through a sample of exporting a gridview to an excel spreadsheet.
I found the code below on the internet. I pasted it into a test.aspx page.
I need to establish a connection to the NorthWind Database.  Can you help me with the code? 
Or if you have a better example of exporting a gridview to excel, please share.

Here is the location of the northwind.mdb on my pc:  (and is this sample looking for an access database or a sql database...what is the filetype of a sqlserver database?)   See code below

c:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\QuickStart\aspnet\samples\data\app_data\northwind.mdb


<%@ Import Namespace="System.IO" %>
<script language="VB" Runat="server">
Sub doExcel(Source as Object, E as EventArgs)
If gv.Rows.Count.ToString + 1 < 65536 Then
Dim tw As New StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim frm As HtmlForm = new HtmlForm()
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("content-disposition", "attachment;filename=" & txtFile.text & ".xls")
Response.Charset = ""
EnableViewState = False

View Complete Post

More Related Resource Links

display data into GridView from excel sheet

I have to display data from excel sheet into my gridview and also I need to figure out a way to store data into excel files from my web page. I am using C# 3.5, VS 2008.

Gridview that exports selected rows to Excel

his seems like a messy workaround, but I ended up using two Gridviews - one to display my data and show my checkboxes, and the other which was invisible amd would eventually end up as my Excel spreadsheet.

Export Gridview data to Excel sheet


Hi ,

     I have a requirement where i need to export the gridview data to excel.My code export the data in excel that was fine.

But the enchancement needed now , I was exporting the 3 gridview in same excel sheet under the workbook.

Now i need to export the 3 grid view in 3 different sheet in the same workbook.

so can please tell or share the updated code in my below code ...

public void writeovrsummary()


        Response.Write("Overall Summary");
        //Response.Write("Report as of " + DateTime.Now.ToString("hh:mm ss tt"));

        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        SqlCommand com = MyConnection.CreateCommand();
        com.CommandText = "useroverall_Report";
        SqlParameter[] par = new SqlParameter[1];
        par[0] = new

Excel-like experience - gridview focus problem



I'm creating a page where people can order several items from a list without having to press "edit" and "save" in between like you normally would in a gridview. The user writes down the quantity, and finally presses a "submit" button that saves the order.

I want the user to have a windows form (or excel) like eperience, so once the user puts in the quantity and moves on to the next item, either by TAB or by clicking on the TextBox, i make some calculations without the user beeing bothered with a full refresh or having to press a buton to execute the event, so I place the controls inside an UpdatePanel and use TextBox.TextChanged. The event runs code that calculates the sum for the row (price * quantity) and shows that in a column called "Sum", and updates a label in a fixed position with the new order total ("Total").

Any ideas on how to achieve this?

Right now I use a GridView with a templatefield for the Quantity and set the TextBox.TextChanged event to fire to make the calculations. The problem is that the focus then changes.

By using SmartNavigation or the ScriptManager.SetFocus I manage to retain focus on the TextBox that executed the Postback, but the user might have moved on to a textbox far down the gridview (thus causing the postback by leaving the previo

Export altered gridview to Excel


Hello... stuck on this one!!  In a gridview RowDataBound named gvwResult I am altering one of the cells with a value retrieved from the query.

I have added:

if (hdnExchangeTo.Value.ToString() != "1")
            for (int i =0; i < gvwResult.Rows.Count; i++)
                gvwResult.Rows[i].Cells[7].Text = ExchangeCurrency(gvwResult.Rows[i].Cells[7].Text.ToString());

to the common code to export to Excel:

        Response.Buffer = true;
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        System.IO.StringWriter sw = new Syste

Sample: Business Connectivity Services Excel 2010 Add-In

Download a sample add-in that shows how to use BCS in SharePoint Server 2010 to access and update external data by using Microsoft Excel 2010 as a client.

Sample: Developing Applications in SharePoint 2010 Using Word Automation Services and Excel Services

Download sample code that demonstrates the new client services features that are available in SharePoint Server 2010, including Word Automation Services and Excel Services.

Sample: Publishing Excel 2007 Workbooks to SharePoint Server 2007

Explore the code in this visual how-to article as you learn how to publish Excel 2007 Workbooks to SharePoint Server 2007 programmatically.

String Data missing start from "+" When Export Data To Excel Using Gridview

Hi,I am exporting data from gridview to excel file.My problem is that for all the string which contain "+", the rest of data begining from it is missing in excel file.For example: PWE-WER+78, when exported it will become PWE-WER.Below is my code.                Response.ClearContent() Response.Buffer = True Response.AddHeader("Content-Disposition", "attachment;filename=" & "ExportedExcel.xls") Response.ContentType = "application/vnd.ms-excel" Response.Charset = "" lobjStringWriter = New StringWriter lobjHtmlWriter = New HtmlTextWriter(lobjStringWriter) dgdResult.RenderControl(lobjHtmlWriter) Response.Write(lobjStringWriter.ToString()) Response.End() I  have search through online but no solution.Does anyone has idea on this?

How to export gridview to excel template

I have a gridview that I need to export to Excel. Excel is not installed on the server, but I would like to put a template on the server so that when the user exports the data it will use the template and open the file on the user's local machine. To make things slightly more complex, I need to export the data to Sheet2 because Sheet1 needs to be a graph (thus the need for the template). I cannot use any third party software and I have no ability to modify anything on the server. This is used in a corporate environment on a shared server that I don't have any control over. Any sample code would be very helpful. I'm running ASP.NET 3.5 with Visual Studio 2008.

ASP.NET-Gridview - Export to excel- column format

Hi All, I am exporting gridview data into excel sheet. I have a column  which is a code for which data is like 012,013 etc. But when this data is being exported , in the excel sheet I can see the data as 12,13,14. but actually it should be 012.... Is there any way to specify the format of such columns in my datatable so that they are in the same manner as in the database? Please provide some information on this.Thanks in advance.

excel to gridview, lost data?!

I don't know why.... I can't understand I import by fileupload one xls, I open this one and I would connect it to a gridview.Everythings works fine but when I see the gridview I don't understand why some data is not available  HttpPostedFile xls = this.FileUpload1.PostedFile; string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xls.FileName.ToString() + ";Extended Properties=Excel 8.0"; DataTable dt = new DataTable(); DataSet ds = new DataSet(); OleDbConnection oConn = new OleDbConnection(); oConn.ConnectionString = strConn; oConn.Open(); List<string> fogli = new List<string>(); //recupero i nomi dei fogli del file excel dt = oConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,null); foreach (DataRow tt in dt.Rows) { fogli.Add(tt["TABLE_NAME"].ToString()); } dt.Clear(); System.Data.OleDb.OleDbDataAdapter ExcelAdapter = new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM [" + fogli[162].ToString() + "]", oConn); ExcelAdapter.Fill(ds); gvExcel.DataSource = ds.Tables[0].DefaultView; gvExcel.DataBind();First I get the name of all the sheets and after I fill one

How do I display excel, pdf and word binary data in a gridview?


Hello forum

I'm using the following code to upload images, pdf files, word files and excel to a sql table as binary data.  However, I can only figure out how to display the images but am clueless about the other type of files.  What adjustments do I need to make so that with a button click I can access the other files?  't By the way, I'm using an image control to display the binary data and I'm aware that that will only work to display images, I just don't how to access all the other types of files once uploaded. Thanks

Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Data.SqlClient
Imports System.IO

Partial Class Uploads_UReceipts
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Request.QueryString("ImageID") IsNot Nothing Then

            Dim strQuery As String = "select Name, ContentType, Data from tblFiles where id=@id"

            Dim cmd As SqlCommand = New SqlCommand(strQuery)

            cmd.Parameters.Add("@id", SqlDbType.Int).Va

gridview export to excel


The export to excel work successfully, but a name like this D'Costa is converted to Dâ?TCosta.

Any name with the tick converts within excel. Is there a fix?



Merge Columns Like Excel In Gridview


Hello everybody.

I have a excel file which is in structure a class routine:

                  | 9-10 | 10-11 | 11-12 | 12-01 | 01-02 | 02-03 | 03-04 | 04-05 |

tue             |           subject1                      |     subject2     |    subject3      |

wed            |   subject2     |                subject3                   |    subject1      |

thu             |            subject3        |     subject2     |             subject1          

Export a Query to Gridview then Excel


I have not done this before so pardin this question that I am sure has been asked before.

I have a user that asks me to run queries each month and copy & paste the data into a spreadsheet

I want to set up the queries in a web page for him to choose, enter the data in the parameters

and either show the data in a gridview then export or just export to the spreadsheet

direclty to the file name and location of his choice.

Using C#

Links or code samples would great.

Export GridView to Excel using .net 2010 (C#)


Can anyone tell me how to export gridview to excel using asp.net 2010? C# is the script language

what i have is working in VS2008 but not working in VS2010:

 public override void VerifyRenderingInServerForm(Control control)

after clicking the button:





Response.Charset = "" ;

Response.ContentEncoding = System.Text.Encoding .UTF8;

Response.Charset = "" ;

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend