Powered by Blogger.

Sunday, February 23, 2014

Export Data Of DataGridview To Excel using C# Windows Appllication



In this post we will discuss how to export Data Of DataGridview To Excel using C# Windows Appllication.

Also check out:

- How to display serial number automatically in GridView in asp.net?

- Write exception to Event Log in Asp.Net C#.Net

- Increase column size in sql server 2008

Namespaces
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.IO;

Function For  Exporting To Excel
private void ToCsV(DataGridView data, string file)
        {
            string stOutput = "";
            string sHeaders = "";

            for (int j = 0; j < data.Columns.Count; j++)
                sHeaders = sHeaders.ToString() + Convert.ToString(dataColumns[j].HeaderText) + "\t";
            stOutput += sHeaders + "\r\n";
         
            for (int i = 0; i < dataRowCount - 1; i++)
            {
                string stLine = "";
                for (int j = 0; j < data.Rows[i].Cells.Count; j++)
                    stLine = stLine.ToString() + Convert.ToString(data.Rows[i].Cells[j].Value) + "\t";
                stOutput += stLine + "\r\n";
            }
            Encoding utf16 = Encoding.GetEncoding(1254);
            byte[] output = utf16.GetBytes(stOutput);
            FileStream fs = new FileStream(filename, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(output, 0, output.Length);
            bw.Flush();
            bw.Close();
            fs.Close();
        }

Code For Button On Export To Excel
         

           SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter = "Excel Documents (*.xls)|*.xls";

            sfd.FileName = "export.xls"; // Default File Name

            if (sfd.ShowDialog() == DialogResult.OK)
            {

                ToCsV(dataGridView1, sfd.FileName);
            }
MessageBox.Show("Data Exported");

Output