C# Perform a Search in Excel

Sometimes there is a need to interact with an Excel file through our application. The purpose of this example is to show how this is possible. We will use ADO.Net, namely the OleDb namespace used to manage Microsoft Access files. This namespace provides classes that we can use to interact with data sources from the Excel, Access and other file types. We analyze this code where we find the OleDbConnection and OleDbCommand classes that are the main historical instruments with which we connect to a data source.

  1. private DataSet _ds;  
  2. private DataTable _tb;  
  3. private BindingSource _bs;  
  4.   
  5. private void Form1Load(object sender, EventArgs e)  
  6. {  
  7.     _ds = new DataSet();  
  8.     _tb = new DataTable();  
  9.     _bs = new BindingSource();  
  10.   
  11.     var myConnection = new OleDbConnection(@"provider=Microsoft.ACE.OLEDB.12.0;data source=E:\demo.XLSx;Extended Properties=Excel 12.0;");  
  12.     var myCommand = new OleDbDataAdapter("SELECT * FROM [Foglio1$]", myConnection);  
  13.     myCommand.Fill(_tb);  
  14.     _ds.Tables.Add(_tb);  
  15.     _bs.DataSource = _ds.Tables[0];  
  16. }  

This code will run on a startup application being under the load event of Form1, first declare a DataSet that is null, but a container inside with one or more tables (DataTable) and allows us to work disconnected from the source data.

We declare a DataTable control, consisting of rows and columns where they will end all the information that we read from the data source, in a last control BindingSource, the latter will be used to do the search and display screen information and the search result.

Immediately after using the OleDbConnection class, define the connection string to the data source, it should be called the data provider, the latter varies depending on the version of Excel that we're going to use, in this case being an Excel 2007 file, we will use Microsoft .ACE.OLEDB.12.0, then define the connection string that should correspond to the exact location of the file on disk, note that if the file is not found then it generates a runtime exception of type "File not found exception", then ensure that the file is in the path specified in the connection string.

Afterwards we just need to define the class OledbDataAdapter, representing the controls of a set of data and a database connection used to fill a DataSet and update the data source.

To fill a DataSet, we must start using the Fill method, this command is responsible for filling in the DataSet or DataTable using the Select statement that we set as a parameter in the query class OledbDataAdapter.

At this point, using the Add method, we add a table to the control DataSet and assign the DataSource property of the BindingSource table populated with any information taken from the source data.

After this step we have in memory all the information needed to do a search. Suppose you have a file Excel called demo.xlsx with inside 3 columns, "NOME", "COGNOME" and "MESE".
 
 
We will carry out the search using the BindingSource control, namely the Filter property, let us consider this example code.
  1. private void TextBoxValidated(object sender, EventArgs e)  
  2. {  
  3.     if (ReferenceEquals(sender, txtNome))  
  4.     {  
  5.         Trova((TextBox)sender, "NOME");  
  6.     }  
  7.     else if (ReferenceEquals(sender, txtCognome))  
  8.     {  
  9.         Trova((TextBox)sender, "COGNOME");  
  10.     }  
  11.     else if (ReferenceEquals(sender, txtMese))  
  12.     {  
  13.         Trova((TextBox)sender, "MESE");  
  14.     }  
  15. }  
  16.   
  17. private void Trova(Control textBox, string nomeColonna)  
  18. {  
  19.     _bs.Filter = String.Concat(nomeColonna, " ""LIKE '", textBox.Text, "*'");  
  20.     DataGridView1.DataSource = _bs;  
  21. }  

We manage events Validated TextBox controls txtNome, txtCognome and txtMese, all connected to a Event TextBoxValidated, using the variable sender we go to retrieve the TextBox control and on which ran the event Validated, then calling the method Trova. This method requires two parameters, the first TextBox and that was selected, the second type of research consists of a string of characters, the example and can search by name, last name and Month.

As said, we use the Filter property that gets or sets the expression filter for displaying rows displayed. It is basically a SQL query, but we can also adapt to our needs. To finish the search result it will assign to the DataGridView control using the DataSource property.

To search, you simply type in the text boxes a name, surname or month and the content will be displayed on the control DtaGridView, so if we put the name Carmel and we move to another TextBox then we have this situation.

The following is the complete code.

  1. using System;  
  2. using System.Data;  
  3. using System.Windows.Forms;  
  4. using System.Data.OleDb;  
  5.   
  6. namespace ExcelTextCS  
  7. {  
  8.     public partial class Form1 : Form  
  9.     {  
  10.         private DataSet _ds;  
  11.         private DataTable _tb;  
  12.         private BindingSource _bs;  
  13.   
  14.         public Form1()  
  15.         {  
  16.             InitializeComponent();  
  17.         }  
  18.   
  19.         private void Form1Load(object sender, EventArgs e)  
  20.         {  
  21.             _ds = new DataSet();  
  22.             _tb = new DataTable();  
  23.             _bs = new BindingSource();  
  24.   
  25.             var myConnection = new OleDbConnection(@"provider=Microsoft.ACE.OLEDB.12.0;data source=E:\demo.XLSx;Extended Properties=Excel 12.0;");  
  26.             var myCommand = new OleDbDataAdapter("SELECT * FROM [Foglio1$]", myConnection);  
  27.             myCommand.Fill(_tb);  
  28.             _ds.Tables.Add(_tb);  
  29.             _bs.DataSource = _ds.Tables[0];  
  30.         }  
  31.   
  32.         private void TextBoxValidated(object sender, EventArgs e)  
  33.         {  
  34.             if (ReferenceEquals(sender, txtNome))  
  35.             {  
  36.                 Trova((TextBox)sender, "NOME");  
  37.             }  
  38.             else if (ReferenceEquals(sender, txtCognome))  
  39.             {  
  40.                 Trova((TextBox)sender, "COGNOME");  
  41.             }  
  42.             else if (ReferenceEquals(sender, txtMese))  
  43.             {  
  44.                 Trova((TextBox)sender, "MESE");  
  45.             }  
  46.         }  
  47.   
  48.         private void Trova(Control textBox, string nomeColonna)  
  49.         {  
  50.             _bs.Filter = String.Concat(nomeColonna, " ""LIKE '", textBox.Text, "*'");  
  51.             DataGridView1.DataSource = _bs;  
  52.         }  
  53.     }  
  54. }


Similar Articles