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";
if (sfd.ShowDialog() == DialogResult.OK)
{
ToCsV(dataGridView1, sfd.FileName);
}