Monday, 3 November 2014

Generate Excel file using C#


using Excel = Microsoft.Office.Interop.Excel;

protected void ExportToExcell(object sender, EventArgs e)
{           
            string data = null;
            int i = 0;
            int j = 0;

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

            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

           

            for (i = 0; i <= 10; i++)
            {
                for (j = 0; j <= 5; j++)
                {
                    data = "Ajay " + i.ToString();
                    xlWorkSheet.Cells[i + 1, j + 1] = data;
                    xlWorkSheet.Cells[1, j + 1].Font.Bold = true;
                    xlWorkSheet.Cells[1, j + 1].Interior.ColorIndex = 10;
                }
            }

            xlWorkBook.SaveAs(Server.MapPath("~/Docs/") + "csharp.net-informations.xls",
           Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, 
           Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
  
}



private void releaseObject(object obj)
{
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;       
            }
            finally
            {
                GC.Collect();
            }           

}        

No comments:

Post a Comment