try
{
if (dt == null || dt.Columns.Count == 0)
{
throw new Exception("ExportToExcel: Null or empty input table!\n");
}
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel._Worksheet xlWorkSheet;
Microsoft.Office.Interop.Excel.Range xlRange = null;
object misValue = Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = false;
xlWorkBook = xlApp.Workbooks.Open(FileParth, misValue, false, misValue, misValue, misValue, true, misValue, misValue, misValue, misValue, misValue, false, misValue, misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Sheets[SheetName];
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Sheets[1];
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.ActiveSheet;
xlWorkSheet.Activate();
xlRange = xlWorkSheet.get_Range(StartRange, EndRange);
int i = 0;
int j = 0;
//Header
for (i = 0; i < dt.Columns.Count; i++)
{
xlRange.Cells[1, i + 1] = dt.Columns[i].ColumnName;
}
//Datas
for (i = 0; i < dt.Rows.Count; i++)
{
for (j = 0; j < dt.Columns.Count; j++)
{
xlRange.Cells[i + 2, j + 1] = dt.Rows[i][j];
}
}
if (FileParth != null || FileParth != "")
{
try
{
xlApp.ActiveWorkbook.SaveAs(FileParth);
xlApp.Quit();
xlWorkSheet = null;
xlWorkBook = null;
xlApp = null;
}
catch (Exception ex)
{
throw new Exception("Can not save file" + ex.Message);
}
}
else
{
xlApp.Visible = true;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}