Home » excel » c# – Reading Excel file on condition

c# – Reading Excel file on condition

Posted by: admin April 23, 2020 Leave a comment

Questions:

Hi I’m writing an WinForm application and I want to read an excel file. My excel is something like this:

------------------------------------------------------
first_name |last_name|ID      |Skill   |exam_date |certification_number|
john       |  smith  |12345678|engineer|2013/12/12|3543546647
john       |  smith  |12345678|electronic|2013/07/12|35477776647
.....
.....

because my excel doesn’t have primary key ,as you can see for one person I can have several rows(up to 20) which the first 3 columns are the same .

I wrote this code to read excel but it reads just one row .How can I read all rows with the same ID?

string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\book3.xlsx;Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";
        DataSet ds = new DataSet();
        OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [SHEET1$]", ConnectionString);
        adapter.Fill(ds);

        DataRow dataRow = (from DataRow dr in ds.Tables[0].Rows where dr["ID"].ToString() == textBox1.Text select dr).FirstOrDefault();

Thanks in advance

How to&Answers:

Your FirstOrDefault() only picks the ‘First

try this:

IEnumerable<DataRow> dataRows = (from DataRow dr in ds.Tables[0].Rows where dr["ID"].ToString() == textBox1.Text select dr);
foreach (DataRow dataRow in dataRows)
{
      // do stuff with current dataRow
}

Answer:

var query = from DataRow dr in ds.Tables[0].Rows where dr["ID"].ToString() == textBox1.Text select dr;

foreach (DataRow dataRow in query.ToList())
{
      // do something with dataRow 
}

Answer:

In my C# applications I use the EPPLUS library (http://epplus.codeplex.com/)
It is really good and fast I would say.

Here is my code to open a sheet of a file using EPPLUS and load the data into a DataTable:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Globalization;
using System.Diagnostics;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using OfficeOpenXml.Drawing.Chart;
using System.Xml;

public class ProjectLoad {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath"></param>
        public void Load ( string filePath ) {

            // Get the file we are going to process
            FileInfo existingFile = new FileInfo( filePath );

            try {
                if ( existingFile.Exists == true ) {
                    // Open and read the XlSX file.
                    using ( ExcelPackage package = new ExcelPackage( existingFile ) ) {
                        // Get the work book in the file
                        ExcelWorkbook workBook = package.Workbook;
                        if ( workBook != null ) {
                            if ( workBook.Worksheets.Count > 0 ) {

                                // read some data
                                int sheet_number = 0;
                                DataTable table = load_sheet_toDataGrid( workBook.Worksheets[sheet_number] );
                            }
                        }
            } catch ( System.IO.IOException ) {
                //error message
            }

        }

        /// <summary>
        /// loads the content of a sheet into a datatable
        /// </summary>
        /// <param name="currentWorksheet"></param>
        /// <returns></returns>
        private DataTable load_sheet_toDataGrid ( ExcelWorksheet currentWorksheet ) {
            DataTable dt = new DataTable( );

            int rows = currentWorksheet.Dimension.End.Row;
            int cols = currentWorksheet.Dimension.End.Column;

            //Add columns
            for ( int c = 0 ; c < cols ; c++ ) {
                dt.Columns.Add( currentWorksheet.Cells[0 + 1 , c + 1].Value.ToString( ) );
            }

            //add values
            for ( int r = 1 ; r < rows ; r++ ) {
                object[] ob = new object[cols];
                for ( int c = 0 ; c < cols ; c++ ) {

                    double value;
                    bool isDouble = Double.TryParse( currentWorksheet.Cells[r + 1 , c + 1].Value.ToString( ) , out value );

                    bool isDate = false;
                    DateTime date = new DateTime( );
                    if ( c == 0 && !isDouble ) {
                        isDate = DateTime.TryParse( currentWorksheet.Cells[r + 1 , c + 1].Value.ToString( ) , out date );
                    }

                    if ( isDouble ) {
                        ob[c] = value;
                    } else if ( isDate ) {
                        ob[c] = date;
                    } else {
                        ob[c] = currentWorksheet.Cells[r + 1 , c + 1].Value;
                    }
                }
                dt.Rows.Add( ob );
            }

            return dt;  
       }
}