-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.

Venil Aravazhi
  • 289
  • 3
  • 7
  • 16

1 Answers1

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.

Daniel Abou Chleih
  • 2,440
  • 2
  • 19
  • 31
  • 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. http://www.aspdotnet-suresh.com/2013/01/c-microsoft-office-access-database.html. Still am getting the same exception. File path: E:\09-2013\SalesRep. File name: Openleads.xlsx. Kindly help me to solve this? – Venil Aravazhi Sep 04 '13 at 13:28
  • 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 – Daniel Abou Chleih Sep 04 '13 at 13:37