Search EggHeadCafe's Job Board
EggHeadCafe Silverlight WPF ASP.NET VB.NET C# Excel SQL Server SharePoint
search
MicrosoftArticlesForumsFAQs
C# .NET
VB.NET
Visual Studio .NET
ADO.NET
Xml / Xslt
VB 6.0
.NET CF
GDI+
LINQ
Deployment
Security
FoxPro
Silverlight / WPF
Entity Framework
RIA Services

WebArticlesForumsFAQs
JavaScript
ASP
ASP.NET
WCF

DatabasesArticlesForumsFAQs
SQL Server
Access
Oracle
MySQL
Other Databases

OfficeArticlesForumsFAQs
Excel
Word
Powerpoint
Outlook
Publisher
Money

Non-MicrosoftArticlesForumsFAQs
NHibernate
Perl
PHP
Ruby
Java
Linux / Unix
Apple
Open Source

Operating SysArticlesForumsFAQs
Windows 7
Windows Server
Windows Vista
Windows XP
Windows Update
MAC
Linux / UNIX

Server PlatformsArticlesForumsFAQs
BizTalk
Site Server
Exhange Server
IIS

Graphic DesignArticlesForumsFAQs
Macromedia Flash
Adobe PhotoShop
Expression Blend
Expression Design
Expression Web

OtherArticlesForumsFAQs
Lounge
Subversion / CVS
Ask Dr. Dotnetsky
Active Directory
Networking
Uninstall Virus
Job Openings
Product Reviews
Search Engines
Resumes

 

  View Other C# .NET Posts   Ask New Question  Ask New Question With Power Editor

exporting gridview data to excel sheet
santoshk kumar posted at Monday, July 14, 2008 10:46 AM

how to export grid veiw data to excel sheet in windows application through C#.net

 

Reply    Reply Using Power Editor
  Rank Winnings Points
November 0 $0.00 0
October 0 $0.00 0
Here you go
Jason S provided a rated reply to santoshk kumar on Monday, July 14, 2008 11:00 AM

string attachment = "attachment; filename=Contacts.xls";

Response.ClearContent();

Response.AddHeader("content-disposition", attachment);

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

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

GridView1.RenderControl(htw);

Response.Write(sw.ToString());

Response.End(); 

If you run the code as above, it will result in an HttpException as follows:

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server." 

To avoid this error, add the following code:  

public override void VerifyRenderingInServerForm(Control control)

{

 

}

 

Step : Convert the contents

 

If the GridView contains any controls, such as Checkboxes, Dropdownlists, we need to replace the contents with their relevant values. The following recursive function uses Reflection to determine the type of control. The control is deleted in preparation for the Excel export and the relevant value of the control is added.

 

private void PrepareGridViewForExport(Control gv)

{

 

    LinkButton lb = new LinkButton();

    Literal l = new Literal();

    string name = String.Empty;

    for (int i = 0; i < gv.Controls.Count; i++)

    {

        if (gv.Controls[i].GetType() == typeof(LinkButton))

        {

            l.Text = (gv.Controls[i] as LinkButton).Text;

  gv.Controls.Remove(gv.Controls[i]);

  gv.Controls.AddAt(i, l);

        }

        else if (gv.Controls[i].GetType() == typeof(DropDownList))

        {

            l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;

            gv.Controls.Remove(gv.Controls[i]);

            gv.Controls.AddAt(i, l);

        }

        else if (gv.Controls[i].GetType() == typeof(CheckBox))

        {

            l.Text = (gv.Controls[i] as CheckBox).Checked? "True" : "False";

            gv.Controls.Remove(gv.Controls[i]);

            gv.Controls.AddAt(i, l);

        }

        if (gv.Controls[i].HasControls())

        {

            PrepareGridViewForExport(gv.Controls[i]);

        }

}

Code Listing:

Image: Page Design

  

Image : Sample in action

Image: Export to Excel button is clicked

Image: GridView contents exported to Excel

ExcelExport.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportExcel.aspx.cs" Inherits="DeleteConfirm" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Contacts Listing</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<strong><span style="font-size: small; font-family: Arial; text-decoration: underline">

Contacts Listing

    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Export To Excel" /></span></strong><br />

<br />

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ContactID"

DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display." style="font-size: small; font-family: Arial" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical">

<Columns>

<asp:BoundField DataField="ContactID" HeaderText="ContactID" ReadOnly="True" SortExpression="ContactID" Visible="False" />

<asp:BoundField DataField="FName" HeaderText="First Name" SortExpression="FName" />

<asp:BoundField DataField="LName" HeaderText="Last Name" SortExpression="LName" />

<asp:BoundField DataField="ContactPhone" HeaderText="Phone" SortExpression="ContactPhone" />

<asp:TemplateField HeaderText="Favorites">

<ItemTemplate>

    &nbsp;

    <asp:CheckBox ID="CheckBox1" runat="server" />

</ItemTemplate></asp:TemplateField>

</Columns>

<FooterStyle BackColor="#CCCC99" />

<RowStyle BackColor="#F7F7DE" />

<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />

<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />

<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />

<AlternatingRowStyle BackColor="White" />

</asp:GridView>

 

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ContactsConnectionString1 %>"

DeleteCommand="DELETE FROM [ContactPhone] WHERE [ContactID] = @ContactID" InsertCommand="INSERT INTO [ContactPhone] ([FName], [LName], [ContactPhone]) VALUES (@FName, @LName, @ContactPhone)"

ProviderName="<%$ ConnectionStrings:ContactsConnectionString1.ProviderName %>"

SelectCommand="SELECT [ContactID], [FName], [LName], [ContactPhone] FROM [ContactPhone]"

UpdateCommand="UPDATE [ContactPhone] SET [FName] = @FName, [LName] = @LName, [ContactPhone] = @ContactPhone WHERE [ContactID] = @ContactID">

<InsertParameters>

<asp:Parameter Name="FName" Type="String" />

<asp:Parameter Name="LName" Type="String" />

<asp:Parameter Name="ContactPhone" Type="String" />

</InsertParameters>

<UpdateParameters>

<asp:Parameter Name="FName" Type="String" />

<asp:Parameter Name="LName" Type="String" />

<asp:Parameter Name="ContactPhone" Type="String" />

<asp:Parameter Name="ContactID" Type="Int32" />

</UpdateParameters>

<DeleteParameters>

<asp:Parameter Name="ContactID" Type="Int32" />

</DeleteParameters>

</asp:SqlDataSource>

&nbsp;

<br />

</div>

</form>

</body>

</html>

ExcelExport.aspx.cs 

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Text;

using System.IO;

 

public partial class DeleteConfirm : System.Web.UI.Page

{

 

    protected void Page_Load(object sender, EventArgs e)

    {

    }

 

    protected void Button1_Click(object sender, EventArgs e)

    {

        //Export the GridView to Excel

        PrepareGridViewForExport(GridView1);

        ExportGridView();

    }

 

    private void ExportGridView()

    {

        string attachment = "attachment; filename=Contacts.xls";

        Response.ClearContent();

        Response.AddHeader("content-disposition", attachment);

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

        StringWriter sw = new StringWriter();

        HtmlTextWriter htw = new HtmlTextWriter(sw);

        GridView1.RenderControl(htw);

        Response.Write(sw.ToString());

        Response.End();

    }

 

    public override void VerifyRenderingInServerForm(Control control)

    {

    }

 

    private void PrepareGridViewForExport(Control gv)

    {

        LinkButton lb = new LinkButton();

        Literal l = new Literal();

        string name = String.Empty;

        for (int i = 0; i < gv.Controls.Count; i++)

        {

            if (gv.Controls[i].GetType() == typeof(LinkButton))

            {

                l.Text = (gv.Controls[i] as LinkButton).Text;

                gv.Controls.Remove(gv.Controls[i]);

                gv.Controls.AddAt(i, l);

            }

            else if (gv.Controls[i].GetType() == typeof(DropDownList))

            {

                l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;

                gv.Controls.Remove(gv.Controls[i]);

                gv.Controls.AddAt(i, l);

            }

            else if (gv.Controls[i].GetType() == typeof(CheckBox))

            {

                l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";

                gv.Controls.Remove(gv.Controls[i]);

                gv.Controls.AddAt(i, l);

            }

            if (gv.Controls[i].HasControls())

            {

                PrepareGridViewForExport(gv.Controls[i]);

            }

        }

    }

}

 

Implementation Options:

 

In quite a few cases, developers face an error in the Export functionality - typically the error message is "RegisterForEventValidation can only be called during Render();".

 

Our website readers have contributed some good suggestions in the article comments below. I would particularly like to highlight the suggestion by Marianna, who provides an alternative implementation to the VerifyRenderingInServerForm override. This approach is described below: 

  • Step 1: Implement the Export functionality as described above.
  • Step 2: Remove the code to override the VerifyRenderingInServerForm method.
  • Step 3: Modify the code for the ExportGridView function as below. The code highlighted in green creates and HtmlForm on the fly, before exporting the gridview, adds the gridview to this new form and renders the form (instead of rendering the gridview in our original implementation) 

private void ExportGridView()

{

          string attachment = "attachment; filename=Contacts.xls";

          Response.ClearContent();

          Response.AddHeader("content-disposition", attachment);

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

          StringWriter sw = new StringWriter();

          HtmlTextWriter htw = new HtmlTextWriter(sw);

 

          // Create a form to contain the grid

          HtmlForm frm = new HtmlForm();

          GridView1.Parent.Controls.Add(frm);

          frm.Attributes["runat"] = "server";

          frm.Controls.Add(GridView1);

 

          frm.RenderControl(htw);

          //GridView1.RenderControl(htw);

          Response.Write(sw.ToString());

          Response.End();

}

Reply    Reply Using Power Editor
  Rank Winnings Points
November 0 $0.00 0
October 0 $0.00 0

i want to in windows application not in asp.net(webforms)
uday shankar replied to Jason S on Monday, July 14, 2008 12:09 PM

    i want to export grid view data from a windows application not in web form 

Reply    Reply Using Power Editor
  Rank Winnings Points
November 0 $0.00 0
October 0 $0.00 0

exporting gridview data to excel sheet
Partha Mandayam replied to santoshk kumar on Monday, July 14, 2008 12:34 PM

Here's a good article. You can directly download the code and use it.

http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html
Reply    Reply Using Power Editor
  Rank Winnings Points
November 0 $0.00 0
October 0 $0.00 0

reply
alice johnson replied to santoshk kumar on Monday, July 14, 2008 12:46 PM

public void ExportToExcel(SqlDataSource dataSrc, string fileName)
{
        //Add Response header
        Response.Clear();
        Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", fileName));
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        //GET Data From Database               
        SqlConnection cn = new SqlConnection(dataSrc.ConnectionString);
        string query = dataSrc.SelectCommand.Replace("\r\n", " ").Replace("\t", " ");
       
        SqlCommand cmd = new SqlCommand(query, cn);
       
        cmd.CommandTimeout = 999999 ;
        cmd.CommandType    = CommandType.Text;
        try
        {
            cn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            StringBuilder sb = new StringBuilder();           
            //Add Header         
            for (int count = 0; count < dr.FieldCount; count++)
            {
                if (dr.GetName(count) != null)
                    sb.Append(dr.GetName(count));
                if (count < dr.FieldCount - 1)
                {
                    sb.Append(",");
                }
            }
            Response.Write(sb.ToString() + "\n");
            Response.Flush();           
            //Append Data
            while (dr.Read())
            {
                sb = new StringBuilder();
              
                for (int col = 0; col < dr.FieldCount - 1; col++)
                {
                    if (!dr.IsDBNull(col))
                        sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
                    sb.Append(",");
                }
                if (!dr.IsDBNull(dr.FieldCount - 1))
                    sb.Append(dr.GetValue(dr.FieldCount - 1).ToString().Replace(",", " "));
                Response.Write(sb.ToString() + "\n");
                Response.Flush();
            }
            dr.Dispose();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            cmd.Connection.Close();
            cn.Close();
        }
        Response.End();
}

Hello go through this artycle:

http://www.codeproject.com/KB/aspnet/Export_large_data_to_xl.aspx

Reply    Reply Using Power Editor
  Rank Winnings Points
November 0 $0.00 0
October 0 $0.00 0

does these work in windows appl;ication
uday shankar replied to alice johnson on Monday, July 14, 2008 1:01 PM

    i want in windows applcation not in web form 
in Windows there willbe no responce ......etcc


i hav to export gridview data from a windows aplication i.ee from windows forms
Reply    Reply Using Power Editor
  Rank Winnings Points
November 0 $0.00 0
October 0 $0.00 0

datagrid export
Partha Mandayam replied to uday shankar on Monday, July 14, 2008 1:07 PM

See this code

http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=778716&SiteID=1
Reply    Reply Using Power Editor
  Rank Winnings Points
November 0 $0.00 0
October 0 $0.00 0

check this
egg egg replied to uday shankar on Tuesday, July 15, 2008 12:05 AM

Check this link which has so many approaches and samples working on Dataview

http://www.soft82.com/download/windows/gridview-to-excel-export-tool/

Reply    Reply Using Power Editor
  Rank Winnings Points
November 9 $17.00 41
October 21 $0.00 11

TRY THIS..
Vasanthakumar D provided a rated reply to uday shankar on Tuesday, July 15, 2008 12:27 AM

   Hi,

Try the below code...

Include Microsoft Excel 10.0 Object Library from Com components to your
project reference.
In this code ticketsList is a data set which is populated and shown in a
grid.
Hope this is helpful.
   Excel.ApplicationClass excel = new Excel.ApplicationClass();
   excel.Application.Workbooks.Add(true);
   DataTable table = ticketsList.Tables[0];
   int cIndex = 0;
   foreach(DataColumn col in table.Columns)
   {
    cIndex++;
    excel.Cells[1,cIndex]=col.ColumnName;
   }
   int rIndex=0;
   foreach(DataRow row in table.Rows)
   {
    rIndex++;
    cIndex=0;
    foreach(DataColumn col in table.Columns)
    {
     cIndex++;
     excel.Cells[rIndex+1,cIndex] = row[col.ColumnName].ToString();
    }
   }
   excel.Save("New.xls");

Reply    Reply Using Power Editor
  Rank Winnings Points
November 0 $0.00 0
October 6 $42.00 145

Gridview data to Excel Sheet
Sanjay Verma replied to santoshk kumar on Tuesday, July 15, 2008 1:23 AM

See this article :: 

http://geekswithblogs.net/azamsharp/archive/2005/12/21/63843.aspx


Or just type "gridview to excel" to the searchbox on top in the eggheadcafe page.
You will find lots of solutions for your problem.

Hope it helps.
Reply    Reply Using Power Editor
Asp.Net Developer
  Rank Winnings Points
November 0 $0.00 0
October 0 $0.00 0

Thanks to Alll who replied and i hav got a sollution chek it out
santoshk kumar replied to uday shankar on Tuesday, July 15, 2008 2:03 AM

private void button1_Click(object sender, EventArgs e)
      
            {

                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Solo Excel (*.xls)|*.xls";
                saveFileDialog1.FileName = "*.xls";
                //saveFileDialog1.InitialDirectory.


                if (saveFileDialog1.ShowDialog()==DialogResult.OK)
                {
                    try
                    {
                        System.IO.StreamWriter sw = new System.IO.StreamWriter(saveFileDialog1.FileName);

                        sw.WriteLine("<?xml version='1.0'?>");
                        sw.WriteLine("<?mso-application progid='Excel.Sheet'?>");
                        sw.WriteLine("<ss:Workbook xmlns:ss='urn:schemas-microsoft-com:office:spreadsheet'>");
                        sw.WriteLine(" <ss:Styles>");
                        sw.WriteLine(" <ss:Style ss:ID='1'>");
                        sw.WriteLine(" <ss:Font ss:Bold='1'/>");
                        sw.WriteLine(" </ss:Style>");
                        sw.WriteLine(" </ss:Styles>");
                        sw.WriteLine(" <ss:Worksheet ss:Name='Sheet1'>");
                        sw.WriteLine(" <ss:Table>");
                        for (int i = 0; i < dataGridView1.Columns.Count; i++)
                        {
                            sw.WriteLine("<ss:Column ss:Width='{0}'/>", dataGridView1.Columns[i].Width);
                        }
                        sw.WriteLine("<ss:Row ss:StyleID='1'>");

                        for (int i = 0; i < dataGridView1.Columns.Count; i++)
                        {
                            sw.WriteLine(String.Format(("<ss:Cell>")));

                            sw.WriteLine(String.Format(("<ss:Data ss:Type=\"String\">{0}</ss:Data>"), (dataGridView1.Columns[i].HeaderText)));

                            sw.WriteLine(String.Format(("</ss:Cell>")));

                        }

                        sw.WriteLine("</ss:Row>");

                        for (int intFila = 0; intFila < dataGridView1.RowCount - 1; intFila++)
                        {
                            sw.WriteLine(String.Format("<ss:Row ss:Height ='{0}'>", dataGridView1.Rows[intFila].Height));

                            for (int intColumna = 0; intColumna < dataGridView1.Columns.Count; intColumna++)
                            {

                                sw.WriteLine(String.Format(("<ss:Cell>")));

                                sw.WriteLine(String.Format(("<ss:Data ss:Type=\"String\">{0}</ss:Data>"), (dataGridView1[intColumna, intFila].Value.ToString())));

                                sw.WriteLine(String.Format(("</ss:Cell>")));

                            }

                            sw.WriteLine("</ss:Row>");

                        }

                        sw.WriteLine("</ss:Table>");

                        sw.WriteLine("</ss:Worksheet>");

                        sw.WriteLine("</ss:Workbook>");

                        sw.Close();

                        MessageBox.Show("La informacion ha sido Guardada exitosamente");
                    }
                    catch (IOException)
                    {
                        MessageBox.Show("El archivo esta abierto");
                    }

                }


            }

Reply    Reply Using Power Editor
  Rank Winnings Points
November 0 $0.00 0
October 0 $0.00 0

Reply
alice johnson provided a rated reply to santoshk kumar on Tuesday, July 15, 2008 4:48 AM

This will Help you.
 public static void ExportToExcel(DataSet dataSet, string outputPath)
        {
        
            // Create the Excel Application object
            try
            {
                Excel.ApplicationClass excelApp = new Excel.ApplicationClass();

                // Create a new Excel Workbook
                Excel.Workbook excelWorkbook = excelApp.Workbooks.Add(Type.Missing);

                int sheetIndex = 0;

                // Copy each DataTable
                foreach (System.Data.DataTable dt in dataSet.Tables)
                {

                    // Copy the DataTable to an object array
                    object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];

                    // Copy the column names to the first row of the object array
                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        rawData[0, col] = dt.Columns[col].ColumnName;
                    }

                    // Copy the values to the object array
                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        for (int row = 0; row < dt.Rows.Count; row++)
                        {
                            rawData[row + 1, col] = dt.Rows[row].ItemArray[col];
                        }
                    }

                    // Calculate the final column letter
                    string finalColLetter = string.Empty;
                    string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                    int colCharsetLen = colCharset.Length;

                    if (dt.Columns.Count > colCharsetLen)
                    {
                        finalColLetter = colCharset.Substring((dt.Columns.Count - 1) / colCharsetLen - 1, 1);
                    }

                    finalColLetter += colCharset.Substring((dt.Columns.Count - 1) % colCharsetLen, 1);

                    // Create a new Sheet
                    Excel.Worksheet excelSheet = (Excel.Worksheet)excelWorkbook.Sheets.Add(excelWorkbook.Sheets.get_Item(++sheetIndex), Type.Missing, 1, Excel.XlSheetType.xlWorksheet);
                    excelSheet.Name = dt.TableName;

                    // Fast data export to Excel
                    string excelRange = string.Format("A1:{0}{1}", finalColLetter, dt.Rows.Count + 1);

                    excelSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;
                    // Mark the first row as BOLD
                    ((Excel.Range)excelSheet.Rows[1, Type.Missing]).Font.Bold = true;
                }

                // Save and Close the Workbook
                excelWorkbook.SaveAs(outputPath, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                excelWorkbook.Close(true, Type.Missing, Type.Missing);
                excelWorkbook = null;

                // Release the Application object
                excelApp.Quit();
                excelApp = null;

                // Collect the unreferenced objects
                GC.Collect();
                GC.WaitForPendingFinalizers();
                MessageBox.Show("The Search Result Has Been Stored TO Location " + outputPath, " Resume Parser", MessageBoxButtons.OK, MessageBoxIcon.Information);


            }
            catch (Exception ex)
            {
              
                MessageBox.Show("Error in Excel Operation: " + ex.ToString(), "Resume Parser", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
          
        }
Reply    Reply Using Power Editor
  Rank Winnings Points
November 0 $0.00 0
October 0 $0.00 0

Reply
alice johnson replied to santoshk kumar on Tuesday, July 15, 2008 4:48 AM

This will Help you.
 public static void ExportToExcel(DataSet dataSet, string outputPath)
        {
        
            // Create the Excel Application object
            try
            {
                Excel.ApplicationClass excelApp = new Excel.ApplicationClass();

                // Create a new Excel Workbook
                Excel.Workbook excelWorkbook = excelApp.Workbooks.Add(Type.Missing);

                int sheetIndex = 0;

                // Copy each DataTable
                foreach (System.Data.DataTable dt in dataSet.Tables)
                {

                    // Copy the DataTable to an object array
                    object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];

                    // Copy the column names to the first row of the object array
                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        rawData[0, col] = dt.Columns[col].ColumnName;
                    }

                    // Copy the values to the object array
                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        for (int row = 0; row < dt.Rows.Count; row++)
                        {
                            rawData[row + 1, col] = dt.Rows[row].ItemArray[col];
                        }
                    }

                    // Calculate the final column letter
                    string finalColLetter = string.Empty;
                    string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                    int colCharsetLen = colCharset.Length;

                    if (dt.Columns.Count > colCharsetLen)
                    {
                        finalColLetter = colCharset.Substring((dt.Columns.Count - 1) / colCharsetLen - 1, 1);
                    }

                    finalColLetter += colCharset.Substring((dt.Columns.Count - 1) % colCharsetLen, 1);

                    // Create a new Sheet
                    Excel.Worksheet excelSheet = (Excel.Worksheet)excelWorkbook.Sheets.Add(excelWorkbook.Sheets.get_Item(++sheetIndex), Type.Missing, 1, Excel.XlSheetType.xlWorksheet);
                    excelSheet.Name = dt.TableName;

                    // Fast data export to Excel
                    string excelRange = string.Format("A1:{0}{1}", finalColLetter, dt.Rows.Count + 1);

                    excelSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;
                    // Mark the first row as BOLD
                    ((Excel.Range)excelSheet.Rows[1, Type.Missing]).Font.Bold = true;
                }

                // Save and Close the Workbook
                excelWorkbook.SaveAs(outputPath, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                excelWorkbook.Close(true, Type.Missing, Type.Missing);
                excelWorkbook = null;

                // Release the Application object
                excelApp.Quit();
                excelApp = null;

                // Collect the unreferenced objects
                GC.Collect();
                GC.WaitForPendingFinalizers();
                MessageBox.Show("The Search Result Has Been Stored TO Location " + outputPath, " Resume Parser", MessageBoxButtons.OK, MessageBoxIcon.Information);


            }
            catch (Exception ex)
            {
              
                MessageBox.Show("Error in Excel Operation: " + ex.ToString(), "Resume Parser", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
          
        }
Reply    Reply Using Power Editor
  Rank Winnings Points
November 0 $0.00 0
October 0 $0.00 0

error in Exporting gridview data to excel sheet when using the above code
santoshk kumar replied to alice johnson on Wednesday, July 16, 2008 5:19 AM

iam getting an exception

the file you are trying to open is in diff format than specified by the file extension

Reply    Reply Using Power Editor
  Rank Winnings Points
November 0 $0.00 0
October 0 $0.00 0

hi
alice johnson replied to santoshk kumar on Wednesday, July 16, 2008 6:30 AM

    Send me all that u have written

Reply    Reply Using Power Editor
  Rank Winnings Points
November 0 $0.00 0
October 0 $0.00 0