mercredi 25 avril 2012

Lire les données d'un fichier Excel (. Xls) dans ASP.NET

Dans cet article, nous allons voir comment afficher des données à partir d'un fichier Excel en utilisant ASP.NET. Nous allons nous connecter au fichier Excel à l'aide du moteur de données OLEDB.NET, extraire les données, puis afficher les données dans un GridView.

1.ajouter dans le fichier web.config


<connectionStrings>
            <add name="xls" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Sample1.xls;Extended Properties=Excel 8.0"/>
            <add name="xlsx" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Sample.xlsx;Extended Properties=Excel 12.0"/>
      </connectionStrings> 

2. CodeSources
protected void Page_Load(object sender, EventArgs e)
    {
        string connString = ConfigurationManager.ConnectionStrings["xls"].ConnectionString;
       
        OleDbConnection oledbConn = new OleDbConnection(connString);
        try
        {
            // ouverture connection
            oledbConn.Open();
            // Creation OleDbCommand
            OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
            // Create new OleDbDataAdapter
            OleDbDataAdapter oleda = new OleDbDataAdapter();
            oleda.SelectCommand = cmd;
          
            DataSet ds = new DataSet();
           
            oleda.Fill(ds, "Employees");
            GridView1.DataSource = ds.Tables[0].DefaultView;
            GridView1.DataBind();
        }
        catch
        {
        }
        finally
        {
            // fermeture connection
            oledbConn.Close();
        }     
    }

Aucun commentaire:

Enregistrer un commentaire