Friday, September 14, 2018

How To Read Data From Excel Sheet Using C#

1. Create the new window application in visual studio

2. Add The Reference Microsoft.Office.Interop.Excel from reference tab in Solution Explorer
Right click on the reference then click on the add reference
click on the Microsoft.Office.Interop.Excel  Then click ok
now your excel reference is added.

3. Create the excel file and save it into the debug folder in your project
   excelExample\bin\Debug




4. Now write the following code in your form.cs file

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using _Excel = Microsoft.Office.Interop.Excel;
using System.IO;

namespace excelExample
{
    public partial class Form1 : Form
    {
     
        string excelFile = "";
        public Form1()
        {
            InitializeComponent();
            excelFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "excelFile.xlsx");
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
             _Excel.Application xlApp;
            _Excel.Workbook xlWorkBook;
            _Excel.Worksheet xlWorkSheet;
            xlApp = new Microsoft.Office.Interop.Excel.Application();
            xlWorkBook = xlApp.Workbooks.Open(excelFile);
            xlWorkSheet = (_Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            string name = "";
            name = xlWorkSheet.Cells[2, 1].Value;
            MessageBox.Show("Name Is "+name);
         
            xlWorkBook.Close();

        }
    }
}

5. Output:-



No comments:

Post a Comment

Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...