Home  »  Articles  »  C#.Net  »

Create Excel file in C# using interop service

 Posted By : Manoranjan SahooPosted Date : 20/04/2011 10:49:43 AM Category : C#.Net Points : 8 (Rs 5.00)

Here i am going to explain how to create one excel file in C#.net using microsoft office interop service.

Download Full Source Code

To Create Excel file follow the below steps :

Step 1 : Add the Microsoft Excel 12.0 Object Library to your project.

  • Create a new project and add a Command Button to the Form.
  • To add Excel reference library in to your project see below picture.

 

Step 2 : Select Add Reference dialogue from Website Menu

Step 3 : Select Microsoft.Excel 12.0 Object Library and click OK button

Step 4 : Now add Interop.Excel.dll to your projects bin folder and then add the reference to Interop.Excel.dll

To make reference to Interop.Excel.dll follow the same steps as above but instead of choose COM tab select Browse tab and then you can navigate to your bin folder and then click on Interop.Excel.dll and then click on OK

Download Interop.Excel.dll file here : Interop.Excel

Then Use the below code to create a simple excel file and save it to c drive :

Code :

protected void Button1_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Add(misValue);

        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        xlWorkSheet.Cells[1, 1] = "Sample Data";

        xlWorkBook.SaveAs("c:\\csharp-Excel.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();
        }
    }

You can download full version of working example from below links :

1. http://uploading.com/files/ma48c1cm/CreateExcelFile.zip/

2. http://www.filesonic.com/file/1459731874/CreateExcelFile.zip

Responses
No responses found for this thread. Be the first to respond this thread.
Post Reply
Login to post Response.