I am familiar with Excel VBA but new to C# and Visual Basicvisula Studio. I have an Excel file (.xlsm) with several sheets. Using ExcelDataReader, I managed to build a solution to show all sheet names in a combobox control. I need help in how can I import the selected sheet content in combobox (cboSheet) to the datagridview1
using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace ReadandImportsheet1
{
public partial class Form1 : Form
{
private readonly object con;
public object Break { get; private set; }
public Form1()
{
InitializeComponent();
}
public Form1(object con)
{
this.con = con;
}
private void button1\_Click(object sender, EventArgs e)
{
OpenFileDialog fil = new OpenFileDialog();
fil.ShowDialog();
string path = fil.FileName.ToString();
ExcelFileReader(path);
}
public void ExcelFileReader(string path)
{
var stream = File.Open(path, FileMode.Open, FileAccess.Read);
var reader = ExcelReaderFactory.CreateReader(stream);
var result = reader.AsDataSet();
var tables = result.Tables;
foreach (DataTable table in tables)
{
cboSheet.Items.Add(table.TableName);
}
//var shname = cboSheet.SelectedValue;
//string table\_name = cboSheet.Text;
}
private void cboSheet\_SelectedIndexChanged(object sender, EventArgs e)
{
string table\_name = cboSheet.Text;
SqlConnection Con = new SqlConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = path; Extended Properties = "Excel 8.0; HDR = YES";");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select \* from " + table\_name + " ", con);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables\[0\];
dataGridView1.DataBind();
con.Close();
}
}
}
I am using Win 11 and Visual Studio 2019 with ExcelDataReade