Export Data Of DataGridview To Excel using C#.Net Windows Application

This C#.net tutorial, we will discuss how to Export Data Of DataGridview To Excel using C#.Net Windows Application.

Below is the full code to Export Data Of DataGridview To Excel using C#.Net Windows Application.

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

Export Data Of DataGridview To Excel using C#.Net Windows Application

You may like following .Net tutorials:

This tutorial, we leanred how to export Data Of DataGridview To Excel using C#.Net Windows Application.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>