vendredi 1 juin 2012

Lire les données d'une feuille Excel avec asp.net

Il est possible de lire les données d'une feuille Excel avec asp.net et meme plus d'effectuer une recherche à l'intérieur d'une feuille excel de la meme facon qu'on le ferait dans une base des données. La différence entre la lecture dans une feuille excele et dans une  base des données est que la base des données offre beacup de souplesse , de rapidité , beaucoup de fonctions de manipulations, de calculs dans un temps très reduit avant même l'affichage devant l'écran de l'utilisateur final. 

Voici comment je me suis battu pour parvenir a lire les données d'une feuille excel

0. Name space à ajouter :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Xml;
using System.Text;
using System.Data.OleDb;
using System.Configuration;
using System.Data;






1. Partie HTML 


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

<style type="text/css">
tr.sectiontableentry1 td,
tr.sectiontableentry2 td {
  padding: 4px;
  font-family:Trebuchet MS;
    font-size:10px;
}
tr.sectiontableentry1 td {
    padding: 8px 5px;
    background: url(hline.gif) repeat-x bottom;
    font-family:Trebuchet MS;
    font-size:10px;
}
tr.sectiontableentry2 td {
    padding: 8px 5px;
    background: url(hline.gif) repeat-x bottom #F2F2F2;
    font-family:Trebuchet MS;
    font-size:10px;
}
</style>

    <title></title>

</head>
<body>
    <form id="form1" runat="server">

    <div>
  
          <table style="padding: 5px; font-size: 11px;">
        
                <tbody>
              
                <tr>
              
                    <td>
                  
                        <strong>Veuillez selectionner un fichier excel.</strong>
                    </td>
                </tr>
                    <tr>
                        <td>
                        <div style="background: url(hline.gif) repeat-x bottom #F2F2F2;padding: 8px 5px;border-bottom: 1px solid #ccc;">
                            <asp:FileUpload ID="txtFilePath" runat="server"></asp:FileUpload>&nbsp;&nbsp;<asp:Button
                                ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
                            <br />
                            <asp:Label ID="lblMessage" runat="server" Visible="False" Font-Bold="True"
                                ForeColor="#009933"></asp:Label>
                        </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                        <asp:GridView ID="grvExcelData" runat="server">
                        <RowStyle CssClass="sectiontableentry2" />
                        <AlternatingRowStyle CssClass="sectiontableentry1" />
                        </asp:GridView>                          
                        </td>
                    </tr>
                </tbody>
            </table>
  


    </div>

    </form>
</body>
</html>

 
2. Partie Code

protected void btnUpload_Click(object sender, EventArgs e)
        {


            try
            {
                if ((txtFilePath.HasFile))
                {

                    OleDbConnection conn = new OleDbConnection();
                    OleDbCommand cmd = new OleDbCommand();
                    OleDbDataAdapter da = new OleDbDataAdapter();
                    DataSet ds = new DataSet();
                    string query = null;
                    string connString = "";
                    string strFileName = DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss");
                    string strFileType = System.IO.Path.GetExtension(txtFilePath.FileName).ToString().ToLower();

                    //Verifions le type de fichier ( excel 1997-2003 ou Excel 2010 ?)
                    if (strFileType == ".xls" || strFileType == ".xlsx")
                    {
                        txtFilePath.SaveAs(Server.MapPath("~/UploadedExcel/" + strFileName + strFileType));
                    }
                    else
                    {
                        lblMessage.Text = "Seulement les fichiers excels sont permis";
                        lblMessage.ForeColor = System.Drawing.Color.Red;
                        lblMessage.Visible = true;
                        return;
                    }

                    string strNewPath = Server.MapPath("~/UploadedExcel/" + strFileName + strFileType);

                    //Etablissons la Connection String Excel
                    if (strFileType.Trim() == ".xls")
                    {
                        connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                    }
                    else if (strFileType.Trim() == ".xlsx")
                    {
                        connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                    }


                    query = "SELECT * FROM [Sheet1$]";

                    //Creons l'objet de connexion
                    conn = new OleDbConnection(connString);
                    //Open connection
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    //Creons l'objet command
                    cmd = new OleDbCommand(query, conn);
                    da = new OleDbDataAdapter(cmd);
                    ds = new DataSet();
                    da.Fill(ds);

                    grvExcelData.DataSource = ds.Tables[0];
                    grvExcelData.DataBind();

                    lblMessage.Text = "Fichier chargé avec succès ! Total d'enregistrement:" + ds.Tables[0].Rows.Count;
                    lblMessage.ForeColor = System.Drawing.Color.Green;
                    lblMessage.Visible = true;

                    da.Dispose();
                    conn.Close();
                    conn.Dispose();
                }
                else
                {
                    lblMessage.Text = "Vous devez d'abord selectionner un fichier Excel";
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    lblMessage.Visible = true;
                }

            }

            catch (Exception Except)
            {

                throw;
            }

        }







Si l'article vous semble utile ou si vous avez des commentaires à faire ou si vous avez des difficultés n'hésitez pas à me contatcter : monsar04atgmail.com / 00243997647154


Aucun commentaire:

Enregistrer un commentaire