Click here to Skip to main content
16,015,177 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I am binding the gridview with data in some columns and rows (i.e 6 columns and 10 rows). Now i need to perform the below tasks.
1. I need to export the gridview data to excel file. The exported data need to be placed in excel sheet with specific format. i.e
1. Header Columns contain Bold Font and Background color (any specific color).
2. In details for each column row, based on some conditions, i need to make a Colored the Font of cell with any Background color (The cell contain any data).
I request please help me on this.
Thanks
Mahesh
Posted

Here's sample code..This was done directly on the form..but its easily modifiable to be used with Classes and Objects..(I've included both Windows form app and ASP.NET app)

1. For Windows Form Application...
C#
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel; 
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        // From Database to DataGridView
        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection cnn ;
            string connectionString = null;
            string sql = null;
            connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";
            cnn = new SqlConnection(connectionString);
            cnn.Open();
            sql = "SELECT * FROM Product";
            SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
            DataSet ds = new DataSet();
            dscmd.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0];
        }

        // From Datagrid View to Excel
        private void button2_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp ;
            Excel.Workbook xlWorkBook ;
            Excel.Worksheet xlWorkSheet ;
            object misValue = System.Reflection.Missing.Value;
            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            int i = 0;
            int j = 0; 
            for (i = 0; i <= dataGridView1.RowCount  - 1; i++)
            {
                for (j = 0; j <= dataGridView1.ColumnCount  - 1; j++)
                {
                    DataGridViewCell cell = dataGridView1[j, i];
                    xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
                }
            }
            xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();
            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
            MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.xls");
        }
        
/* Releasing System Resources (Interop Objects Garbage Collection) */
        
        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}


2. For ASP.NET application..
C#
private void toExcel()
   {
       Response.Clear();
       Response.Buffer = true;
       //Response.Charset = "UTF-8";
       Response.AppendHeader("Content-Disposition", "attachment;filename=schoolsinfo.xls");
       Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
       Response.ContentType = "application/ms-excel";
       this.EnableViewState = false;
       System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("EN-US", true);
       System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
       System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
       GridView1.RenderControl(oHtmlTextWriter);
       Response.Write(oStringWriter.ToString());
   }

Besides, the important issue about this is needed to pay attention: the format of data which is from dataview to excel cell output. So if the data format output in Excel is incorrect, you can configure the DataGrid1_ItemDataBound Event to inder to define the data format:

C#
private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        e.Item.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");// This can convert the data in Number to in Text.
        e.Item.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
    }
}


If the above helps..Accept answer and Vote..:)
 
Share this answer
 
v2
Comments
Dalek Dave 3-Sep-10 11:13am    
Good Answer!
Look at this article . The trick in Cell Formatting should help you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900