Error while trying to read excel file C #

2
public partial class FrmEditar : Form
{
    private OleDbConnection _olecon;
    private OleDbCommand _oleCmd;
    private static string _arquivo = string.Empty;
    private string _stringConexao = string.Empty;
    private string _consulta;

    public FrmEditar()
    {
        InitializeComponent();
    }

    private void btnSelecionarExcel_Click(object sender, EventArgs e)
    {

        OpenFileDialog vAbreArq = new OpenFileDialog
        {
            //Filter = "*.xls | Microsoft Excel| *.xlsx | Microsoft Excel",
            Title = Resources.frmEditar_btnSelecionarExcel_Click_Selecione_o_Arquivo,
            RestoreDirectory = true
        };

        if (vAbreArq.ShowDialog() == DialogResult.OK)
        {
            try
            {
                _arquivo = vAbreArq.FileName;
                _stringConexao = $@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={_arquivo};Extended Properties='Excel 12.0 Xml;HDR=YES;ReadOnly=False';";
                _olecon = new OleDbConnection(_stringConexao);
                _olecon.Open();

                _oleCmd = new OleDbCommand
                {
                    Connection = _olecon,
                    CommandType = CommandType.Text
                };


                txtExcel.Text = vAbreArq.FileName;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }       

    private void btnFechar_Click(object sender, EventArgs e)
    {
        Close();
    }

    private void btnBuscar_Click(object sender, EventArgs e)
    {
        try
        {
            _oleCmd.CommandText = "SELECT CodFunci, NomeFunci FROM [Empregados$] Where CodFunci = " + txtCodigo.Text;
            OleDbDataReader reader = _oleCmd.ExecuteReader(); \Erro acontece nessa linha.

            while (reader != null && reader.Read())
            {
                txtCodigo.Text = reader.GetValue(0).ToString();
                txtNome.Text = reader.GetString(1);
            }

            reader?.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

The error that happens is:

Employees $ is a not valid name. Make sure that it does not include invalid characters or punctuation and that is not too long.

The name of the worksheet I'm using is Employees.xlsx

    
asked by anonymous 08.01.2017 / 21:03

1 answer

5

Empregados$ must be the name of the worksheet in file and not the name of the file, eg

In the example file above, you would have to use Planilha1$

    
08.01.2017 / 21:10