Reading and displaying an xlsx file

This code demonstrates how to read and display xlsx files in a datagridview control. Before you start, please install the Microsoft Access Database Engine 2010 Redistributable, if you do not want to get an error message: "The 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine."

GUI:

DataGridView (DataGidView1), BindingNavigator (bn), Binding source (bs)



source


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;


namespace xlsx_reader1
{
    public partial class Form1 : Form
    {
        string connectionString;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
		dataGridView1.DataSource = bs;
		bn.BindingSource=bs;
        }

        DataTable readXlsx()
        {
            using (OleDbConnection cnn = new OleDbConnection(connectionString))
            {
                cnn.Open();
                var sheets = cnn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                string cmd = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";
                OleDbDataAdapter da = new OleDbDataAdapter(cmd, cnn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt;
            }
        }

        private void Openxlsxfile_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "*.xlsx|*.xlsx";
            if (of.ShowDialog() == DialogResult.OK)
            {
                connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + of.FileName + ";" + "Extended Properties='Excel 12.0 Xml;HDR=NO;IMEX=1;'";
                bs.DataSource = readXlsx();
            }
        }
    }
}