After selecting the excel file with OpenFileDialog, I want to see the worksheet names and select the worksheet page I want. How can we fix these codes according to my request?
private void button2_Click(object sender, EventArgs e)
{
try
{
System.Threading.Thread.Sleep(1000);
// Dosya seçme penceresi açmak için
OpenFileDialog file = new OpenFileDialog
{
Filter = "Excel Dosyasi |*.xls;*.xlsx"
};
file.ShowDialog();
string tamYol = file.FileName;
string baglantiAdresi = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + tamYol + ";Extended Properties='Excel 12.0;IMEX=1;'";
OleDbConnection baglanti = new OleDbConnection(baglantiAdresi);
OleDbCommand komut = new OleDbCommand("Select * From [" + "Sayfa1" + "$]", baglanti);
baglanti.Open();
OleDbDataAdapter da = new OleDbDataAdapter(komut);
DataTable data = new DataTable();
da.Fill(data);
dataGridView1.DataSource = data;
data.Dispose();
baglanti.Close();
komut.Parameters.Clear();
}
catch (Exception ex)
{
// Hata alirsak ekrana bastiriyoruz.
MessageBox.Show("Dosya Seçilmedi!Hata :" + ex.Message);
}
}
Mehmet FatihPosted Apr 4, 2024, 9:11 AM
Thanks for your intrest Mithelesh Tata.IT was solved.
Mithilesh TataPosted Apr 4, 2024, 8:34 AM
To achieve your request, you need to modify the code to first retrieve the worksheet names from the selected Excel file and then allow the user to choose the desired worksheet. Here's how you can do it:
In this code, I've added a new method
ChooseWorksheetwhich creates a form displaying the names of all the worksheets in the selected Excel file. The user can then select the desired worksheet from a dropdown list. The selected worksheet name is returned to thebutton2_Clickmethod, and the data from that worksheet is then loaded into theDataGridView.