SoFunction
Updated on 2025-03-07

Two ways to export Excel in DataGridView in C#

The first is to export using data streams:

#region
      SaveFileDialog saveFileDialog = new SaveFileDialog();
       = "Execl files (*.xls)|*.xls";
       = 0;
       = true;
       = true;
       = "Export Excel File";
      ();
      if ( == "")
        return;
      Stream myStream;
      myStream = ();
      StreamWriter sw = new StreamWriter(myStream, (-0));
 
      string str = "";
      try
      {
        for (int i = 0; i < ; i++)
        {
          if (i > 0)
          {
            str += "\t";
          }
          str += [i].HeaderText;
        }
        (str);
        for (int j = 0; j < ; j++)
        {
          string tempStr = "";
          for (int k = 0; k < ; k++)
          {
            if (k > 0)
            {
              tempStr += "\t";
            }
            tempStr += [j].Cells[k].();
          }
          (tempStr);
        }
        ();
        ();
      }
 
      catch (Exception ex)
      {
        //(());
      }
      finally
      {
        ();
        ();
      }
#endregion

The advantage of this method is that it exports faster, but you can't set titles, font styles, etc. in Excel tables, because you use data streams to export directly to Excel, unless you can set these styles in the data stream. I don't have this skill yet. Which brother can teach you... Hey hey

The second method is to directly write a class, which directly operates on EXCEL:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
 
namespace Excel
{
  public class Export
  {
    /// &lt;summary&gt;
    /// DataGridView Export Excel    /// &lt;/summary&gt;
    /// <param name="strCaption">Title in Excel file</param>    /// <param name="myDGV">DataGridView control</param>    /// <returns>0:Successful; 1:No record in DataGridView; 2: Excel cannot start; 9999:Exception error</returns>    public int ExportExcel(string strCaption, DataGridView myDGV, SaveFileDialog saveFileDialog)
    {
      int result = 9999;
      
      //save      
       = "Execl files (*.xls)|*.xls";
       = 0;
       = true;
      // = true;
       = "Export Excel File";
      if ( ()== )
      {
        if ( == "")
        {
          ("Please enter the save file name!");
          ();
        }
          // Column index, row index, total number of columns, total number of rows        int ColIndex = 0;
        int RowIndex = 0;
        int ColCount = ;
        int RowCount = ;
 
        if ( == 0)
        {
          result = 1;
        }
 
        // Create Excel object         xlApp = new ();
        if (xlApp == null)
        {
          result = 2;
        }
        try
        {
          // Create Excel workbook           xlBook = (true);
           xlSheet = ()[1];
          // Set the title           range = xlSheet.get_Range([1, 1], [1, ColCount]); //The number of cells occupied by the title is the same as the number of columns in the DataGridView           = true;
          .FormulaR1C1 = strCaption;
           = 20;
           = true;
           = ;
          // Create cached data          object[,] objData = new object[RowCount + 1, ColCount];
          //Get the column title          foreach (DataGridViewColumn col in )
          {
            objData[RowIndex, ColIndex++] = ;
          }
          // Get data          for (RowIndex = 1; RowIndex &lt; RowCount; RowIndex++)
          {
            for (ColIndex = 0; ColIndex &lt; ColCount; ColIndex++)
            {
              if (myDGV[ColIndex, RowIndex - 1].ValueType == typeof(string)
                || myDGV[ColIndex, RowIndex - 1].ValueType == typeof(DateTime))//This is to verify the type in the DataGridView cell. If it is a string or DataTime type, add " " before the content when put into the cache;              {
                objData[RowIndex, ColIndex] = "" + myDGV[ColIndex, RowIndex - 1].Value;
              }
              else
              {
                objData[RowIndex, ColIndex] = myDGV[ColIndex, RowIndex - 1].Value;
              }
            }
            ();
          }
          // Write to Excel          range = xlSheet.get_Range([2, 1], [RowCount, ColCount]);
          range.Value2 = objData;
 
           = true;
          ();
        }
        catch (Exception err)
        {
          result = 9999;
        }
        finally
        {
          ();
          (); //Forced recycling        }
        //Return value        result = 0;
      }
      
      return result;
    }
 
 
  }
}

This advantage is that it can set styles or something. The disadvantage is that the export speed is slow...

The above two methods are referenced by a lot of materials.. Written here to facilitate mutual learning..

To add: using the second method to export Excel will have format changes, such as the ID number is derived according to scientific algorithms, not according to the original model.

The improvement is to add a format declaration when writing to excel: = "@";

For example: // Write to Excel

range = xlSheet.get_Range([2, 1], [RowCount + 2, ColCount]);
 = "@";
range.Value2 = objData;

This is the end of this article about two methods of exporting Excel by DataGridView in C#. For more related C# DataGridView to export Excel, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!