Logré importartar un archivo excel a un 'DataGridView', solo que tengo un problema, me gustaría poder importar cualquier archivo 'Excel' sin importar el nombre de la hoja por que por ahora solo puedo importar archivos que tengan como nombre [Sheet$].
Este es mi código:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
namespace ImportarExcelToDatagridview
{
class Importar
{
OleDbConnection conn;
OleDbDataAdapter MyDataAdapter;
DataTable dt;
public void importarExcel(DataGridView dgv,String nombreHoja)
{
String ruta = "";
try
{
OpenFileDialog openfile1 = new OpenFileDialog();
openfile1.Filter = "Excel Files |*.xlsx";
openfile1.Title = "Seleccione el archivo de Excel";
if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (openfile1.FileName.Equals("") == false)
{
ruta = openfile1.FileName;
}
}
conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=" + ruta + ";Extended Properties='Excel 12.0 Xml;HDR=Yes'");
MyDataAdapter = new OleDbDataAdapter("Select * from [Sheet$]", conn);
dt = new DataTable();
MyDataAdapter.Fill(dt);
dgv.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}