Export From DataGridView To Excel-Sheet in C#

using Excel = Microsoft.Office.Interop.Excel;  // Add Refference of Microsoft.Office.Interop.Excel.dll

// The Data that would be in the DataGridView will be Export to Excel Sheet. By
private void ExportToExcel () //Here ‘gridview_newadmission’ is the Name of the DataGridView
{

try
{

Microsoft.Office.Interop.Excel.Application xlApp; Microsoft.Office.Interop.Excel.Workbook xlWorkBook; Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value;

xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

for (int c = 0; c < gridview_newadmission.ColumnCount; c++)
{

xlWorkSheet.Cells[1, c + 1] = gridview_newadmission.Rows[0].Cells[c].OwningColumn.Name.ToString();
xlWorkSheet.Cells.ColumnWidth = 15;

}

for (int r = 0; r < gridview_newadmission.RowCount; r++)
{

for (int c = 0; c < gridview_newadmission.ColumnCount; c++)
{

DataGridViewCell cell = gridview_newadmission[c, r];
xlWorkSheet.Cells[r + 2, c + 1] = cell.Value;

}

}

FolderBrowserDialog SelectTarget = new FolderBrowserDialog();
SelectTarget.ShowDialog();
string path = SelectTarget.SelectedPath;
if (path != “”)
{

xlWorkBook.SaveAs(path + “\\myData.xls”, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

}
statusMessage.ForeColor = Color.Black;
statusMessage.Text = “Data Saved to ” + path;

 }
catch (Exception)
{}

}

DataGridView To Datatable in C#

public DataTable DataGridView2DataTable(DataGridView dgv, String tblName, int minRow=0)//Simply Use this Function For Conversion it would return Datatble
{

DataTable dt = new DataTable(tblName);

  // Header columns
foreach (DataGridViewColumn column in dgv.Columns)
{

DataColumn dc = new DataColumn(column.Name.ToString());
dt.Columns.Add(dc);

}

// Data cells
for (int i = 0; i < dgv.Rows.Count; i++)
{

DataGridViewRow row = dgv.Rows[i];
DataRow dr = dt.NewRow();
for (int j = 0; j < dgv.Columns.Count; j++)
{

dr[j] = (row.Cells[j].Value == null) ? “” : row.Cells[j].Value.ToString();

}

dt.Rows.Add(dr);
}

// Related to the bug arround min size when using ExcelLibrary for export
for (int i = dgv.Rows.Count; i < minRow; i++)
{

DataRow dr = dt.NewRow();
for (int j = 0; j < dt.Columns.Count; j++)
{

dr[j] = ”  “;

}
dt.Rows.Add(dr);

}
return dt;

}