Saturday 17 May 2014

Creating Excel file in C#


The following section explains how to create an Excel file programmatically using C#. Before you create an Excel file in C# , you have to add the Microsoft Excel 12.0 Object Library to you project.
Create a new project and add a Command Button to the Form. Form the following pictures you can find how to add Excel reference library in your project. Select reference dialogue from Project menu Select Microsoft Excel 12.0 Object Library and click OK button





Copy and paste the following source code in your C# project file.

using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace WinFormsExcelDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("Please Give a name for Excel");
                textBox1.Focus();
            }
            else
            {
                Excel.Application xlapp;
                Excel.Workbook xlworkbook;
                Excel.Worksheet xlworksheet;
                object misvalue = System.Reflection.Missing.Value;
                //xlapp = new Excel.ApplicationClass(); 
                xlapp = new Excel.Application();
                xlworkbook = xlapp.Workbooks.Add(misvalue);
                xlworksheet = (Excel.Worksheet)xlworkbook.Worksheets.get_Item(1);
                xlworksheet.Cells[1, 1] = " New Work sheet";
                xlworkbook.SaveAs(textBox1.Text + ".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);
                MessageBox.Show("Excel file created , you can find the file in Documents");
            }
        }
        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception occured while releasing object"+ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }


Note : You have to add Microsoft.Office.Interop.Excel to your source code.
using Excel = Microsoft.Office.Interop.Excel;
When you execute this program , it will create an excel file in you c:\Documents