Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Excel 2013 File in ASP.NET

Tags:

c#

asp.net

excel

I am developing an ASP.NET application. I have an Excel 2013 file named ExcelApp and i have also added in my project. I can not access the file.

Here is my DAL class:

public string ExcelConnection = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Nimit\ExcelApplication.xlsx;Extended Properties='Excel 12.0 Xml';HDR=YES"; 
    OleDbDataAdapter DbAdap;
    DataTable dt;

    public DataTable Get_ExcelSheet()
    {
        OleDbConnection DbCon = new OleDbConnection(ExcelConnection);

        DbAdap = new OleDbDataAdapter("SELECT * FROM [Sheet1$]",DbCon);
        dt = new DataTable();
        DbAdap.Fill(dt);
        return dt;
    }

My cs file code:

public partial class WebForm1 : System.Web.UI.Page
{
    DAL obj = new DAL();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack == true)
        {
            Get_Data();
        }
    }

    void Get_Data()
    {
        GridView1.DataSource = obj.Get_ExcelSheet();
        GridView1.DataBind();
    }
}

My debugger shows the error while executing this line:

DbAdap.Fill(dt);

The exception is:

enter image description here

like image 287
Nimit Joshi Avatar asked Jan 17 '26 20:01

Nimit Joshi


2 Answers

I solved my question. Here is my code:

public class DAL
{
    OleDbDataAdapter DbAdap;
    DataTable dt;

    public DataTable Get_ExcelSheet()
    {
        OleDbConnection DbCon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Nimit\\ExcelApplication.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"");

        DbAdap = new OleDbDataAdapter("SELECT * FROM [Sheet1$]",DbCon);
        dt = new DataTable();
        DbAdap.Fill(dt);
        return dt;
    }
}

I simply provide my connection string in my OleDbConnection. Thats it.

like image 128
Nimit Joshi Avatar answered Jan 20 '26 10:01

Nimit Joshi


I think you should read again the exception. There is a clear message why this code fails you... I'll give you a hint:

Additiona information: The "Microsoft.ACE.OLEDB.40' provider is not registered on the local machine

Fix that and it should work.

like image 20
Dawid Avatar answered Jan 20 '26 08:01

Dawid