Tuesday, September 18, 2018

Read Data from Excel file and fill to comboBox in c#

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)
        {
            fillComboBox();
        }

            protected void fillComboBox()
        {
            _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);

            for (int i = 2; i < 10; i++)
            {
                comboBox1.Items.Add(xlWorkSheet.Cells[i, 1].Value.ToString());
               
            }
            xlWorkBook.Close();
        }
    }
}


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...