I have solved the problem as given below
public void ExportToExcel(List<Employee> objEmployee)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Workbooks.Add();
Microsoft.Office.Interop.Excel._Worksheet workSheet = excel.ActiveSheet;
try
{
workSheet.Cells[1, "A"] = "ID";
workSheet.Cells[1, "B"] = "Name";
workSheet.Cells[1, "C"] = "Address";
workSheet.Cells[1, "D"] = "State";
workSheet.Cells[1, "E"] = "Country";
int row = 2;
foreach (BusinessModels.Employee emp in objEmployee)
{
workSheet.Cells[row, "A"] = emp.ID;
workSheet.Cells[row, "B"] = emp.Name;
workSheet.Cells[row, "C"] = emp.Address;
workSheet.Cells[row, "D"] = emp.State;
workSheet.Cells[row, "E"] = emp.Country;
row++;
}
workSheet.Range["A1"].AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1);
string fileName = string.Format(@"{0}\ExportedData.xlsx", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
if (File.Exists(fileName))
{
File.Delete(fileName);
}
workSheet.SaveAs(fileName);
ExcelMessages.ErrorMessage = (string.Format("The file '{0}' is saved successfully!", fileName));
}
catch (Exception exception)
{
throw new Exception("There was a PROBLEM saving Excel file!\n" + exception.Message);
}
finally
{
excel.Quit();
if (excel != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
if (workSheet != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
excel = null;
workSheet = null;
GC.Collect();
}
}