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.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Windows.Forms;  
using Microsoft.Office.Interop.Excel;  
using System.IO;namespace Export_Excel  
{  
    class moduleExcel  
    {  
        public void ToCsV(DataGridView dgv,string name, string age,string address,string title,string filename)  
        {       
            //========Data from textbox==========//        
            string stOutput = "";  
            string stTitle = "";  
            string sHeaders = "";  
            string stName = "";  
            string stAge = "";  
            string stAdrress = "";  
            stTitle = "\r\n" + title + "\r\n\n";  
            stName = "\n" + name +"\r";  
            stAdrress = "\n" + address +"\r";  
            stAge = "\n" + age +"\r";  
            stOutput += title;  
            stOutput += stName;  
            stOutput += stAdrress;  
            stOutput += stAge;  
            for (int j = 0; j < dgv.Columns.Count; j++)  
                sHeaders = sHeaders.ToString() + Convert.ToString(dgv.Columns[j].HeaderText) + "\t";  
            stOutput += sHeaders + "\r\n";  
            // Export data.  
            for (int i = 0; i < dgv.RowCount - 1; i++)  
            {  
                string stLine = "";  
                for (int j = 0; j < dgv.Rows[i].Cells.Count; j++)  
                    stLine = stLine.ToString() + Convert.ToString(dgv.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); //write the encoded file  
            bw.Flush();  
            bw.Close();  
            fs.Close();  
        }               private Worksheet FindSheet(Workbook workbook, string sheet_name)  
        {  
            foreach (Worksheet sheet in workbook.Sheets)  
            {  
                if (sheet.Name == sheet_name) return sheet;  
            }            return null;  
        }        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();  
            }  
        }  
      
    }  
}

Step 6

Next, go back to the windows form and view the code to write the following program listing:

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;namespace Export_Excel  
{  
    public partial class Form1 : Form  
    {  
        moduleExcel excelImp = new moduleExcel();        public Form1()  
        {  
            InitializeComponent();  
        }        private void staticDatagrid()  
        {  
            dataGridView1.Rows.Add("1","Book 1");  
            dataGridView1.Rows.Add("2","Book 2");  
        }        private void button1_Click(object sender, EventArgs e)  
        {  
              
            string title = " Excel Export by Camellabs";  
            SaveFileDialog sfd = new SaveFileDialog();  
            sfd.Filter = "Excel Documents (*.xls)|*.xls";  
            sfd.FileName = "camellabs.xls";  
            if (sfd.ShowDialog() == DialogResult.OK)  
            {  
                excelImp.ToCsV(dataGridView1,textBox1.Text, textBox2.Text, textBox3.Text,title, sfd.FileName);     
                  MessageBox.Show("Finish");  
            }  
        }        private void Form1_Load(object sender, EventArgs e)  
        {  
            staticDatagrid();  
        }  
         
    }  
} 

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 Github Here.

Thank you for reading this article, I hope it was useful for you. Visit My Github about .Net Csharp Here.


Similar Articles