C# Export to Excel from Datagridview

Introduction 

 
This article is about a C# export to Excel from datagridview. Automation of an Excel file allows us to do various operations from C#. We can automate an Excel file from C# in two ways. W ith the Excel Object Model, one way is to use the Microsoft Jet Engine to connect Excel from CSharp. Through the automation from C#, we can create a new workbook, add data to a workbook, create charts, etc.
 

How to Export Datagridview?

 
Excel Interop
 
Often, we work with MS Office tools like Word, Excel, PPT, etc. There is a definitive way to work with these applications using the .NET Framework.
Let’s follow the tutorial below in order to convert Excel with a C# application.
 
Step 1
 
Create a new application project. In Visual Studio, on the menu click File> New > Project. For more details, see the following menu on the display.
 
C# Export To Excel From Datagridview
 
Step 2
 
Then the window New Project will appear, which should look like the image below:
 
C# Export To Excel From Datagridview
 
Step 3
 
Write down the name of the project that will be created. Specify the directory storage project by accessing the field Location. Next, give the name of the solution in the Solution Name. Then click OK.
 
C# Export To Excel From Datagridview
 
Step 4
 
Create a new windows form like shown below:
 
C# Export To Excel From Datagridview
 
Step 5
 
Create a new class with the name moduleExcel.cs for declaring the functions from the connection Excel interop.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Windows.Forms;  
  6. using Microsoft.Office.Interop.Excel;  
  7. using System.IO;namespace Export_Excel  
  8. {  
  9.     class moduleExcel  
  10.     {  
  11.         public void ToCsV(DataGridView dgv,string name, string age,string address,string title,string filename)  
  12.         {       
  13.             //========Data from textbox==========//        
  14.             string stOutput = "";  
  15.             string stTitle = "";  
  16.             string sHeaders = "";  
  17.             string stName = "";  
  18.             string stAge = "";  
  19.             string stAdrress = "";  
  20.             stTitle = "\r\n" + title + "\r\n\n";  
  21.             stName = "\n" + name +"\r";  
  22.             stAdrress = "\n" + address +"\r";  
  23.             stAge = "\n" + age +"\r";  
  24.             stOutput += title;  
  25.             stOutput += stName;  
  26.             stOutput += stAdrress;  
  27.             stOutput += stAge;  
  28.             for (int j = 0; j < dgv.Columns.Count; j++)  
  29.                 sHeaders = sHeaders.ToString() + Convert.ToString(dgv.Columns[j].HeaderText) + "\t";  
  30.             stOutput += sHeaders + "\r\n";  
  31.             // Export data.  
  32.             for (int i = 0; i < dgv.RowCount - 1; i++)  
  33.             {  
  34.                 string stLine = "";  
  35.                 for (int j = 0; j < dgv.Rows[i].Cells.Count; j++)  
  36.                     stLine = stLine.ToString() + Convert.ToString(dgv.Rows[i].Cells[j].Value) + "\t";  
  37.                 stOutput += stLine + "\r\n";  
  38.             }            Encoding utf16 = Encoding.GetEncoding(1254);  
  39.             byte[] output = utf16.GetBytes(stOutput);  
  40.             FileStream fs = new FileStream(filename, FileMode.Create);  
  41.             BinaryWriter bw = new BinaryWriter(fs);  
  42.               
  43.             bw.Write(output, 0, output.Length); //write the encoded file  
  44.             bw.Flush();  
  45.             bw.Close();  
  46.             fs.Close();  
  47.         }               private Worksheet FindSheet(Workbook workbook, string sheet_name)  
  48.         {  
  49.             foreach (Worksheet sheet in workbook.Sheets)  
  50.             {  
  51.                 if (sheet.Name == sheet_name) return sheet;  
  52.             }            return null;  
  53.         }        private void releaseObject(object obj)  
  54.         {  
  55.             try  
  56.             {  
  57.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);  
  58.                 obj = null;  
  59.             }  
  60.             catch (Exception ex)  
  61.             {  
  62.                 obj = null;  
  63.                 MessageBox.Show("Exception Occured while releasing object " + ex.ToString());  
  64.             }  
  65.             finally  
  66.             {  
  67.                 GC.Collect();  
  68.             }  
  69.         }  
  70.       
  71.     }  

Step 6
 
Next, go back to the windows form and view the code to write the following program listing:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;namespace Export_Excel  
  9. {  
  10.     public partial class Form1 : Form  
  11.     {  
  12.         moduleExcel excelImp = new moduleExcel();        public Form1()  
  13.         {  
  14.             InitializeComponent();  
  15.         }        private void staticDatagrid()  
  16.         {  
  17.             dataGridView1.Rows.Add("1","Book 1");  
  18.             dataGridView1.Rows.Add("2","Book 2");  
  19.         }        private void button1_Click(object sender, EventArgs e)  
  20.         {  
  21.               
  22.             string title = " Excel Export by Camellabs";  
  23.             SaveFileDialog sfd = new SaveFileDialog();  
  24.             sfd.Filter = "Excel Documents (*.xls)|*.xls";  
  25.             sfd.FileName = "camellabs.xls";  
  26.             if (sfd.ShowDialog() == DialogResult.OK)  
  27.             {  
  28.                 excelImp.ToCsV(dataGridView1,textBox1.Text, textBox2.Text, textBox3.Text,title, sfd.FileName);     
  29.                   MessageBox.Show("Finish");  
  30.             }  
  31.         }        private void Form1_Load(object sender, EventArgs e)  
  32.         {  
  33.             staticDatagrid();  
  34.         }  
  35.          
  36.     }  

Step 7
After you write down the program listings, press the F5 key to run the program. If you run it successfully, the result is:
C# Export To Excel From Datagridview
 
Step 8
 
Click the button “Export Excel” to export data to Microsoft Excel. It will display a dialog result as shown below. You can save the file in your selected document:
 
C# Export To Excel From Datagridview
 
Step 9
 
The file has been saved in your document directory. The result is:
 
C# Export To Excel From Datagridview
 
We have explained how to make a program export data to Microsoft Excel from C# .NET. For those of you who want to download the source code of the program, you also can. Hopefully, this discussion was helpful to you. If you have any questions, you can contact me.
 
You can see the C# Export To Excel From Datagridview project from the Github Here.
 
Thank you for reading this article, I hope it was useful for you. Visit My Github about .Net Csharp Here.