With extension methods you can easily add new methods to existing types without creating new derived type or modifing the original type. Anytime you write a new method that has an input parameter with the keyword: this, is going to be an extension method of the type after the word this.
Here I show you a simple extension method that extends DataTable with a new method called: ExportToExcel
This methods creates a new Excel file from a DataTable. Of course you have to add Microsoft.Office.Interop.Excel as reference and set the following using:
using Excel = Microsoft.Office.Interop.Excel;
and the only static method in your new static class:
public static bool ExportToExcel(this DataTable tbl, string excelFilePath = null) { try { bool result = false; if (tbl == null || tbl.Columns.Count == 0) throw new Exception("No input table!\n"); var excelApp = new Excel.Application(); excelApp.Workbooks.Add(); Excel._Worksheet workSheet = excelApp.ActiveSheet; //heading for (var i = 0; i < tbl.Columns.Count; i++) { workSheet.Cells[1, i + 1] = tbl.Columns[i].ColumnName; } // rows for (var i = 0; i < tbl.Rows.Count; i++) { for (var j = 0; j < tbl.Columns.Count; j++) { workSheet.Cells[i + 2, j + 1] = tbl.Rows[i][j]; } } workSheet.Columns.AutoFit(); if (!string.IsNullOrEmpty(excelFilePath)) { try { workSheet.SaveAs(excelFilePath); excelApp.Quit(); result = true; } catch (Exception ex) { throw new Exception("Excel file could not be saved! Check filepath.\n", ex); } } else { excelApp.Visible = true; } return result; } catch { throw; } }
After all you can use this method this way:
DataTable dt = new DataTable(); ... // your code here that fills up the DataTable ... if (dt.ExportToExcel(saveFileDialog1.FileName)) MessageBox.Show("Completed");