IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

 Delphi Discussion :

[D7] Export d'un StringGrid vers Excel


Sujet :

Delphi

  1. #1
    Membre expert
    Avatar de Charly910
    Homme Profil pro
    Ingénieur TP
    Inscrit en
    Décembre 2006
    Messages
    2 344
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur TP
    Secteur : Bâtiment Travaux Publics

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 344
    Points : 3 122
    Points
    3 122
    Par défaut [D7] Export d'un StringGrid vers Excel
    Bonjour,

    j'exporte le contenu d'un StringGrid vers un fichier Xls à l'aide de ce code :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    { ============================================================================== }
    function TF_Grille.SaveAsExcelFile(AGrid: TStringGrid; AFileName: string): Boolean;
    //     Sauvegarde d'une grille dans un fichier Excel
    // Utilisation : SaveAsExcelFile(StringGrid1,'c:\testxls.xls');
    // La directive $J contrôle si les constantes typées peuvent être modifiées ou non.
    const
      {$J+} CXlsBof: array[0..5] of Word = ($809, 8, 00, $10, 0, 0); {$J-}
      CXlsEof: array[0..1] of Word = ($0A, 00);
    var
      FStream: TFileStream;
      I, J: Integer;
    begin
      FStream := TFileStream.Create(PChar(AFileName), fmCreate or fmOpenWrite);
      try
        CXlsBof[4] := 0;
        FStream.WriteBuffer(CXlsBof, SizeOf(CXlsBof));
        for i := 0 to AGrid.ColCount - 1 do
          for j := 0 to AGrid.RowCount - 1 do
            Begin
              If Pos(sLineBreak , AGrid.cells[i, j]) >0 Then ShowMessage('Oui') ;  // détection du passage à la ligne dans la grille
              XlsWriteCellLabel(FStream, I, J, AGrid.cells[i, j]);
            End ;
        FStream.WriteBuffer(CXlsEof, SizeOf(CXlsEof));
        Result := True;
      finally
        FStream.Free;
      end;
    end;
    { ============================================================================== }
    procedure TF_Grille.XlsWriteCellLabel(XlsStream: TStream; const ACol, ARow: Word; const AValue: string);
    var
      L: Word;
    const
      {$J+}
      CXlsLabel: array[0..5] of Word = ($204, 0, 0, 0, 0, 0);
      {$J-}
    begin
      L := Length(AValue);
      CXlsLabel[1] := 8 + L;
      CXlsLabel[2] := ARow;
      CXlsLabel[3] := ACol;
      CXlsLabel[5] := L;
      XlsStream.WriteBuffer(CXlsLabel, SizeOf(CXlsLabel));
      XlsStream.WriteBuffer(Pointer(AValue)^, L);
    end;
    { ============================================================================== }
    Dans la StringGrid, j'ai des textes sur plusieurs lignes (grâce à sLineBreak)

    à l'export ces textes se retrouvent dans Excel sur une même ligne de la cellule.

    Il faudrait que je remplace les sLineBreak par des Alt+Enter (qui passe à la ligne dans Excel)

    Je ne sais pas comment faire. Quelqu'un a t'il déjà fait ?

    Merci
    A+
    Charly

  2. #2
    Membre éprouvé
    Homme Profil pro
    Chef de projets retraité
    Inscrit en
    Juillet 2011
    Messages
    420
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Cher (Centre)

    Informations professionnelles :
    Activité : Chef de projets retraité
    Secteur : Transports

    Informations forums :
    Inscription : Juillet 2011
    Messages : 420
    Points : 1 102
    Points
    1 102
    Par défaut
    Bonjour,

    Dans Excel c'est juste un saut de ligne (LF (chr(10)).

    Cordialement

  3. #3
    Membre expert
    Avatar de Charly910
    Homme Profil pro
    Ingénieur TP
    Inscrit en
    Décembre 2006
    Messages
    2 344
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur TP
    Secteur : Bâtiment Travaux Publics

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 344
    Points : 3 122
    Points
    3 122
    Par défaut
    Merci Acaumes,

    j'ai déjà essayé Chr(10) pour séparer les lignes, mais quand j'ouvre Excel, tout est sur une même ligne

    Si je me place sur la cellule, les lignes apparaissent séparées dans la ligne de saisie, mais pas dans la cellule ??

    A+
    Charly

  4. #4
    Membre confirmé Avatar de blonde
    Femme Profil pro
    Développeur Delphi
    Inscrit en
    Septembre 2003
    Messages
    278
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Delphi

    Informations forums :
    Inscription : Septembre 2003
    Messages : 278
    Points : 477
    Points
    477
    Par défaut
    Salut,

    j'ai essayé rapidement avec le Chr(10), ça fonctionne bien.
    Par contre, moi dans Excel j'ai l'option "renvoyer automatiquement à la ligne" qui est activée. C'est dans l'onglet "alignement" du ruban principal.
    C'est peut-être ça qui te manque.

  5. #5
    Membre expert
    Avatar de Charly910
    Homme Profil pro
    Ingénieur TP
    Inscrit en
    Décembre 2006
    Messages
    2 344
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur TP
    Secteur : Bâtiment Travaux Publics

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 344
    Points : 3 122
    Points
    3 122
    Par défaut
    Bonjour,

    oui, moi aussi, dans le fichier généré après export, si je fais "Renvoyer automatiquement à la ligne", ça marche, mais j'aurai voulu que cette option soit mise automatiquement dans mon fichier généré quand je l'ouvre.

    ça à l'air plus coton !

    A+
    Charly

  6. #6
    Membre confirmé Avatar de blonde
    Femme Profil pro
    Développeur Delphi
    Inscrit en
    Septembre 2003
    Messages
    278
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Delphi

    Informations forums :
    Inscription : Septembre 2003
    Messages : 278
    Points : 477
    Points
    477
    Par défaut
    Alors ça, modifier les options d'affichage de Excel, je n'ai jamais fait

  7. #7
    Membre confirmé Avatar de blonde
    Femme Profil pro
    Développeur Delphi
    Inscrit en
    Septembre 2003
    Messages
    278
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Delphi

    Informations forums :
    Inscription : Septembre 2003
    Messages : 278
    Points : 477
    Points
    477
    Par défaut
    Sinon, tu peux modifier chaque cellule avec "CellFormat.WrapText property"

    J'ai trouvé ça là : https://docs.microsoft.com/en-us/off...ormat.wraptext

    Et je suppose que tu peux y accéder en OLE.

  8. #8
    Membre expert
    Avatar de Charly910
    Homme Profil pro
    Ingénieur TP
    Inscrit en
    Décembre 2006
    Messages
    2 344
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur TP
    Secteur : Bâtiment Travaux Publics

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 344
    Points : 3 122
    Points
    3 122
    Par défaut
    Oui merci, je vais plutot passer par Ole plutôt que par ce code de la FAQ.

    L'avantage de ce code, c'était que l'on avait pas besoin d'Excel sur le poste. Mais le fichier généré est "rustique"

    A+
    Charly

  9. #9
    Membre éprouvé
    Homme Profil pro
    Chef de projets retraité
    Inscrit en
    Juillet 2011
    Messages
    420
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Cher (Centre)

    Informations professionnelles :
    Activité : Chef de projets retraité
    Secteur : Transports

    Informations forums :
    Inscription : Juillet 2011
    Messages : 420
    Points : 1 102
    Points
    1 102
    Par défaut
    Bonjour,

    Selon la doc Microsoft c'est dans l'enregistrement XF lié à l'enregistrement du LABELSST (7 ème octet de l'enregistrement 3ème bit)
    3 0008h fWrap =1 wrap text in cell.
    On trouve ces informations dans le document Microsoft
    Excel97-2007BinaryFileFormat(xls)Specification
    Cordialement

  10. #10
    Membre expert
    Avatar de Charly910
    Homme Profil pro
    Ingénieur TP
    Inscrit en
    Décembre 2006
    Messages
    2 344
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur TP
    Secteur : Bâtiment Travaux Publics

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 344
    Points : 3 122
    Points
    3 122
    Par défaut
    Merci Acaumes,
    mais je suis incapable de modifier le code FAQ avec ce renseignement

    Il faudrait surement modifier la fonction XlsWriteCellLabel ?

    Si jamais tu sais comment faire ...

    Merci
    A+
    Charly

  11. #11
    Membre émérite

    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2007
    Messages
    3 385
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 62
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2007
    Messages : 3 385
    Points : 2 999
    Points
    2 999
    Par défaut
    Pourquoi ne pas utiliser ADOX ?
    C'est facile et ça génère de vrai fichier excel sans avoir Excel installé sur le poste.

  12. #12
    Membre expert
    Avatar de Charly910
    Homme Profil pro
    Ingénieur TP
    Inscrit en
    Décembre 2006
    Messages
    2 344
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur TP
    Secteur : Bâtiment Travaux Publics

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 344
    Points : 3 122
    Points
    3 122
    Par défaut
    Merci,

    je vais regarder

    A+
    Charly

  13. #13
    Membre expert
    Avatar de Charly910
    Homme Profil pro
    Ingénieur TP
    Inscrit en
    Décembre 2006
    Messages
    2 344
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur TP
    Secteur : Bâtiment Travaux Publics

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 344
    Points : 3 122
    Points
    3 122
    Par défaut
    Finalement j'ai fait ceci qui fonctionne très bien (avec certaines cellules sur plusieurs lignes dans le StringGrid) :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    Procedure TF_Grille.ExportGrilleToExcel(FileName: string; AGrid : TStringGrid);
    // Export de AGrid vers Excel
    const
      xlWBATWorksheet = -4167;
    Var
      XLApp    :variant ;
      WorkBook :variant ;
      Fichier  : String ;
      i, j     : Integer ;
    Begin
      Fichier := RepApp+'\'+ Filename ;
      If FileExists(Fichier) Then DeleteFile(Fichier) ;
      XLApp := CreateOleObject('Excel.Application');
      Try
        WorkBook := XLApp.Workbooks.Add;
        XLApp.ActiveWorkBook.SaveAs(Fichier);
        For i := 0 to AGrid.ColCount - 1 do
          for j := 0 to AGrid.RowCount - 1 do
            XLApp.Cells[j + 1, i + 1].Value := AGrid.Cells[i, j];
        XLApp.ActiveWorkBook.Save;
        XLApp.Workbooks.Close ;
        MessageDlg('Fichier '+ Fichier+ ' enregistré', mtInformation, [mbOk], 0) ;
      Finally
        if not VarIsEmpty(XLApp) then
          begin
            XLApp.DisplayAlerts := False;
            XLApp.Quit;
            XLAPP := Unassigned;
          End ;
      End ;
    End;
    Mais bien sûr Excel doit être installé sur le poste.

    Dommage, j'aurai bien voulu bidouiller dans le fichier XLS de ma première solution !

    Merci à tous

    A+
    Charly

  14. #14
    Membre émérite

    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2007
    Messages
    3 385
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 62
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2007
    Messages : 3 385
    Points : 2 999
    Points
    2 999
    Par défaut
    Je vais essayer de te retrouver un exemple de création avec ADOX.
    Attention, ça n'est intéressant que si tu n'as pas besoin de formater les colonnes, changer les couleurs, etc.

  15. #15
    Membre émérite

    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2007
    Messages
    3 385
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 62
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2007
    Messages : 3 385
    Points : 2 999
    Points
    2 999
    Par défaut
    Alors , dans un premier temps, il faut importer une bibliothèque de types à partir de

    C:\Program Files (x86)\Common Files\System\ado\msadox.dll

    ce qui va te donner accès aux types

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
      Table = _Table;
      Column = _Column;
      Index = _Index;
      Key = _Key;
      Group = _Group;
      User = _User;
      Catalog = _Catalog;
    Après, tu t'inspires du site suivant :

    https://www.swissdelphicenter.ch/en/...de.php?id=1427

    avec la fonction DBGridToExcelADO

  16. #16
    Membre émérite

    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2007
    Messages
    3 385
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 62
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2007
    Messages : 3 385
    Points : 2 999
    Points
    2 999
    Par défaut
    exemple simple :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
     
    var
      cat: _Catalog;
      tbl: _Table;
      col: _Column;
     
    begin
      cat := CoCatalog.Create;
      cat.Set_ActiveConnection(
        'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\creerexcel.xls;Extended Properties=Excel 8.0');
     
        // WorkSheet creation (table)
        tbl := CoTable.Create;
        tbl.Set_Name('Traductions');
     
        col := CoColumn.Create;
        with col do
        begin
          Set_Name('Groupe');
          Set_Type_(adWChar);
        end;
        tbl.Columns.Append(col, adWChar, 500);
     
        col := CoColumn.Create;
        with col do
        begin
          Set_Name('Emplacement');
          Set_Type_(adWChar);
        end;
        tbl.Columns.Append(col, adWChar, 150);
     
        col := CoColumn.Create;
        with col do
        begin
          Set_Name('ID');
          Set_Type_(adInteger);
        end;
        tbl.Columns.Append(col, adInteger, 11);
     
        col := CoColumn.Create;
        with col do
        begin
          Set_Name('Référence');
          Set_Type_(adWChar);
        end;
        tbl.Columns.Append(col, adWChar, 500);
     
        col := CoColumn.Create;
        with col do
        begin
          Set_Name('Traduction');
          Set_Type_(adWChar);
        end;
        tbl.Columns.Append(col, adWChar, 500);
     
        cat.Tables.Append(tbl);
     
        col := nil;
        tbl := nil;
        cat := nil;
    end;
    Nom : 2019-02-26_095222.png
Affichages : 753
Taille : 6,5 Ko

  17. #17
    Membre expert
    Avatar de Charly910
    Homme Profil pro
    Ingénieur TP
    Inscrit en
    Décembre 2006
    Messages
    2 344
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur TP
    Secteur : Bâtiment Travaux Publics

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 344
    Points : 3 122
    Points
    3 122
    Par défaut
    Merci Papy214,

    Je vais tester, mais je n'ai pas un DBGrid, mais un StringGrid ...

    A+
    Charly

  18. #18
    Membre éprouvé Avatar de BuzzLeclaire
    Homme Profil pro
    Dev/For/Vte/Ass
    Inscrit en
    Août 2008
    Messages
    1 606
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Dev/For/Vte/Ass

    Informations forums :
    Inscription : Août 2008
    Messages : 1 606
    Points : 1 113
    Points
    1 113
    Par défaut
    Bonjour Charly,

    J'avais fait cela à l'époque peut-être cela te sera utile pour faire à ta sauce.


    https://www.developpez.net/forums/d6...id-vers-excel/


    Bye

  19. #19
    Membre émérite

    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2007
    Messages
    3 385
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 62
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2007
    Messages : 3 385
    Points : 2 999
    Points
    2 999
    Par défaut
    peut importe la source ! le but est de remplir la feuille excel comme tu remplirais une table.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
     
      ADOConnection                  := TADOConnection.Create(nil);
      ADOConnection.LoginPrompt      := false;
      ADOConnection.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\creerexcel.xls;Extended Properties=Excel 8.0';
      ADOQuery                       := TADOQuery.Create(nil);
      ADOQuery.Connection            := ADOConnection;
     
      // La feuille s'appelle Traduction et il faut kui ajouter un $
      ADOQuery.SQL.Text := 'Select * from [' + 'Traductions' + '$]'
      ADOQuery.Open;
     
      // Groupe, Emplacement, ID, Reference, Trad sont des variables à remplir
      ADOQuery.AppendRecord([Groupe, Emplacement, ID, Reference, Trad]);
     
      ADOQuery.Close;
     
      ADOConnection.Close;

  20. #20
    Membre expert
    Avatar de Charly910
    Homme Profil pro
    Ingénieur TP
    Inscrit en
    Décembre 2006
    Messages
    2 344
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur TP
    Secteur : Bâtiment Travaux Publics

    Informations forums :
    Inscription : Décembre 2006
    Messages : 2 344
    Points : 3 122
    Points
    3 122
    Par défaut
    Ton premier code fonctionne Bien : le fichier d:\creerExcel.xls est bien créé mais si j'exécute une deuxième fois j'ai une erreur :

    EOleException avec : La table traduction existe déjà

    sur cat.Tables.Append(tb1)

    D'autre part, comment remplir une cellule du fichier ? Cells[2,3] par exemple

    A+
    Charly

+ Répondre à la discussion
Cette discussion est résolue.
Page 1 sur 2 12 DernièreDernière

Discussions similaires

  1. Export Multi StringGrid vers Excel
    Par BuzzLeclaire dans le forum Contribuez
    Réponses: 2
    Dernier message: 20/01/2009, 14h09
  2. Réponses: 7
    Dernier message: 22/12/2005, 09h56
  3. Comment exporter un lien hypertexte vers excel
    Par Celia1303 dans le forum Access
    Réponses: 2
    Dernier message: 11/10/2005, 09h33
  4. Exporter un état QuickReport vers Excel.
    Par abdelghani_k dans le forum Bases de données
    Réponses: 3
    Dernier message: 15/06/2004, 14h22
  5. [] [Excel] Exporter un graphe MSChart vers Excel
    Par Gonzo dans le forum Macros et VBA Excel
    Réponses: 4
    Dernier message: 18/12/2002, 17h49

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo