-3

I need to import an excel and have to do some process on it. Those excel data should be retrieved using C#. While i was googled, got confused. Could anybody provide the c# code to achieve it?

Thanks in advance.

0

1 Answer 1

1

Using OleDB:

using System.Data.OleDb;

private void readExcel(string pExcelPath, string pSheetName)
        {
            DataTable sheet1 = new DataTable();
            OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder();
            csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
            csbuilder.DataSource = pExcelPath;
            if (excelFirstRowIsHeader == true)
                csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
            else
                csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=NO");

            using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString))
            {
                connection.Open();
                string sqlQuery = @"SELECT * FROM [" + pSheetName + "]";
                using (OleDbDataAdapter adapter = new OleDbDataAdapter(sqlQuery, connection))
                {
                    adapter.Fill(sheet1);
                    excelData_dataGridView.DataSource = sheet1;
                }
                connection.Close();
            }
        }

This code supports Excel-files created with Excel 2007/2010. The boolean excelFirstRowIsHeader is used to specifiy if your excel contains a header row (if the first row in your excel sheet is used a header)

You can also use Interop-Assembly to read an excel file, but therefor MS Excel must be installed.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your code. While running it, the following exception has been raised. "The Microsoft Office Access database engine cannot open or write to the file 'E:\09-2013\SalesRep'. It is already opened exclusively by another user, or you need permission to view and write its data." I followed this website to solve this problem. aspdotnet-suresh.com/2013/01/…. Still am getting the same exception. File path: E:\09-2013\SalesRep. File name: Openleads.xlsx. Kindly help me to solve this?
Well there could be multiple reasons: 1. The account which is used by IIS does not have the Windows NT permissions for a file-based database or for the folder that contains the file 2. It's really in use by another process 3. The DB is linked to another Database on a network drive. I never had this error

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.