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