Export Datatable To ExcelSheet in C#

public void ExportExcel()
{

try
{

string Apath = “”;

Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Application.Workbooks.Add(true);
// Add column headings…
int iCol = 0;

foreach (DataColumn c in DataTable.Columns)
{

  iCol++;
excel.Cells[1, iCol] = c.ColumnName;

}

// for each row of data…
int iRow = 0;
foreach (DataRow r in DataTable.Rows)
{

iRow++;
// add each row’s cell data…
iCol = 0;
foreach (DataColumn c in UserDT.Columns)
{

iCol++;
excel.Cells[iRow + 1, iCol] = r[c.ColumnName];

}

}
// Global missing reference for objects we are not defining…
object missing = System.Reflection.Missing.Value;

SaveFileDialog save = new SaveFileDialog();
save.Filter = “Xls Files|*.xls”;
save.ShowDialog();
Apath = save.FileName;

// If wanting to Save the workbook.
workbook.SaveAs(Apath,
Excel.XlFileFormat.xlXMLSpreadsheet, missing, missing,false, false, Excel.XlSaveAsAccessMode.xlNoChange,missing, missing, missing, missing, missing);
// If wanting to make Excel visible and activate the worksheet.
excel.Visible = true;
Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet;

((Excel._Application)excel).Quit();

 LblErrorMsg.Text = “Message : Excel Exported…”;

}
catch (Exception)
{

}

}

Write a Comment

Your email address will not be published. Required fields are marked *