How to read Excel file using c#

This is a code read file trainghia.xls and print to console

using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReadExcelFile
{
    class Program
    {
        static void Main(string[] args)
        {
            string con = @”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\p_hung\Desktop\trainghia.xls;Extended Properties=’Excel 8.0;HDR=Yes;'”;
            using (OleDbConnection connection = new OleDbConnection(con))
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand(“select * from [Sheet1$]”, connection);
                using (OleDbDataReader dr = command.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        var row1Col0 = dr[0];
                        Console.WriteLine(row1Col0.ToString());                       
                    }
                }
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *