Thursday, 10 January 2013

Creating Excel file using C#

Step 1: Create a New Project.
Step 2: Right click on the “References” in the “Solution Explorer”.
Step 3: Select “Add Reference”.
Step 4: Select “COM” tab.
Step 5: Select “Microsoft Excel XX.0 Object Library” where XX may be 12 or 14.
Step 6: Write the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// Adding the "Microsoft Excel XX.0 Object Library" dll
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelCreation
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Output File Path: ");
            // The path to create the Excel file along with the total path
            string outputPath = @"" + Console.ReadLine() + "Output.xlsx";

            // Opening Excel Application
            Excel.Application excel = new Excel.Application();
            // Creating Workbook
            Excel._Workbook wb = (Excel._Workbook)(excel.Workbooks.Add(System.Reflection.Missing.Value));
            // Saving Workbook
            wb.SaveAs(outputPath, Excel.XlFileFormat.xlWorkbookDefault, null, null, null, null, Excel.XlSaveAsAccessMode.xlExclusive, null, null, null, null, null);
            // Closing Excel Application
            excel.Quit();

            Console.WriteLine("Success");
        }
    }
}


No comments:

Post a Comment