Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want import Excel sheet from local drive and view in datagrid.

What I have tried:

public void Loadexcel()
        {
            string FileName = "PartList.xlsx";
            String name = "Sheet1";
            String connectionString = "";

            if (FileName.Substring(FileName.LastIndexOf('.')).ToLower() == ".xlsx")
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties=\"Excel 12.0;HDR= YES;IMEX=0\"";
            else
                connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=0\"";

            //string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 XML;HDR=YES;IMEX=1;""", "D:\\PartList.xlsx");

            //string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", txtPath.Text);
            string query = String.Format("select * from [{0}$]", name);

            OleDbConnection con = new OleDbConnection(connectionString);
            System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(query, con);

            ds = new System.Data.DataSet();

            adapter.Fill(ds);



            DataTable dtView = ds.Tables[0];
            if (dtView.Rows.Count > 0)
            {
                dgvPartlist.Rows.Clear();
                dgvPartlist.Rows.Add(dtView.Rows.Count);
                int i = 0;
                foreach (DataRow drow in dtView.Rows)
                {
                    //dgrdReciver.Rows[i].Cells["SerialNo"].Value = j;
                    dgvPartlist.Rows[i].Cells["Sl_No"].Value = drow["Sl_No"];
                    dgvPartlist.Rows[i].Cells["Description"].Value = drow["Description"];
                    dgvPartlist.Rows[i].Cells["Item"].Value = drow["Item"];
                    dgvPartlist.Rows[i].Cells["BEL_Part_No"].Value = drow["BEL_Part_No"];
                     i++;
                }

            }
        }
Posted
Updated 28-Jul-18 6:17am

Maybe you can use the EPPlus library for .NET GitHub - JanKallman/EPPlus: Create advanced Excel spreadsheets using .NET[^]
 
Share this answer
 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900