Transfert rapide des données d'une DataGridView vers Excel

warzet Messages postés 44 Date d'inscription lundi 27 août 2007 Statut Membre Dernière intervention 1 novembre 2016 - 26 août 2013 à 09:20
dodo7263 Messages postés 614 Date d'inscription mercredi 10 septembre 2008 Statut Membre Dernière intervention 9 février 2017 - 6 sept. 2013 à 18:23
Bonjour,
Pour transférer le contenu de mon DataGridView vers Excel, j'utilise la fonction suivante:
        private void Click_Imprimer(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Excel.Application oXL;
            Microsoft.Office.Interop.Excel._Workbook oWB;
            Microsoft.Office.Interop.Excel._Worksheet oSheet;
            Microsoft.Office.Interop.Excel.Range oRng;
            object M = System.Reflection.Missing.Value;

            int i = 0;
            int j = 0;
            int k = 0;

            try
            {
                oXL = new Microsoft.Office.Interop.Excel.Application();
                oXL.Visible = true;

                oWB = oXL.Workbooks.Open(Application.StartupPath + @"/Impressions/Fiche_pp.xls", M, M, M, M, M, M, M, M, M, M, M, M, M, M);
                oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
                oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.Sheets[1];
                oSheet.Name = "Feuil1";
                oSheet.Activate();
                foreach (DataGridViewColumn col in dgvPP.Columns)
                {
                    if (oSheet.Cells[4, 1] != null)
                    {
                        oRng = oSheet.get_Range(Convert.ToChar(65 + i).ToString() + "1", M);
                        oRng.Interior.ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
                        oRng.Font.Bold = true;
                        i++;
                    }
                }
                oSheet.Cells[1, 10] = "Ministère de l'Education Nationale";
                oSheet.Cells[2, 10] = "Direction Régionnale de l'Education Nationale";
                oSheet.Cells[3, 10] = "Collège Racine Divo";
                oSheet.Cells[4, 10] = "Bp 103 Tel/Fax : 32.76.05.26";
                oSheet.Cells[5, 10] = "E-mail : cracinedivo@yahoo.com";
                oSheet.Cells[6, 10] = "D I V O";
                oSheet.Cells[7, 10] = "République de Côte d'Ivoire";
                oSheet.Cells[8, 10] = "Union - Discipline - Travail";
                oSheet.Cells[9, 10] = this.txtClasse.Text;
                oSheet.Cells[10, 10] = this.cboAnneeScolaire.Text;
                oSheet.Cells[11, 10] = this.cboTrimestre.Text;
                oSheet.Cells[12, 10] = string.Concat(this.txtCivilites.Text, " ", this.txtNomEnseignant.Text, " ", this.txtPrenomEnseignant.Text);
                oSheet.Cells[1, 11] = this.txtEffectif_Total.Text;
                oSheet.Cells[2, 11] = this.txtEffectif_Feminin.Text;
                oSheet.Cells[3, 11] = this.txtEffectif_Masculin.Text;
                j = 3;

                foreach (DataGridViewRow uneLigne in dgvPP.Rows)
                {
                    i = 2;
                    int h = 0;

                    if (oSheet.Cells[1, 1] != null)
                    {
                        oRng = oSheet.get_Range(Convert.ToChar(65 + h).ToString() + j.ToString(), M);
                        for (k = 0; k < dgvPP.Rows.Count - 1; k++)
                        {
                            oSheet.Cells[k + 3, 1] = k + 1;
                            oRng.Interior.ColorIndex = Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic;
                            oRng.Font.Bold = false;
                        }
                    }

                    foreach (DataGridViewColumn uneColonne in dgvPP.Columns)
                    {
                        if (oSheet.Cells[j, i] != null)
                        {
                            oRng = oSheet.get_Range(Convert.ToChar(65 + i - 1).ToString() + j.ToString(), M);
                            if (uneLigne.Cells[uneColonne.Name].Value != null) oSheet.Cells[j, i] = "'" + uneLigne.Cells[uneColonne.Name].Value.ToString().Trim();
                            oRng.Font.Bold = false;
                            i++;
                        }
                    }
                    oSheet.Columns.AutoFit();
                    j++;
                }
                oXL.Visible = true;
                oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.Sheets[2];
                oSheet.Name = "FICHE_PP";
                oSheet.Activate();
            }
            catch
            {
            }
        }


Mais lorsqu'on a une DataGridView qui contient 810 enregistrements, il faut environ deux heures 2h00 de temps pour effectuer le transfert entier. Alors si quelqu'un a une méthode un peu plus rapide pour me venir en aide.

3 réponses

BasicInstinct Messages postés 1470 Date d'inscription mardi 5 février 2002 Statut Membre Dernière intervention 20 octobre 2014 12
6 sept. 2013 à 15:07
Bonjour,

3 petits commentaires sur ton probleme :

1) tu parcours un object graphique. C'est à la base une sources de lenteur. Si tes données proviennent d'une datasource, c'est elle qui faut parcourir.

2)Quel version d'excel ? xlsx => c'est du xml. Il faut telecharger le sdk OpenXml. Rien a voir en terme de perf. Ajoute l'avantage de ne pas se soucier de la presence d'excel sur la machine pour generer le document

3) si tu dois etre compatible xls, pas le choix faut passer par les interop (bonjour la prehistoire). Il faut travailler en caché (visible=false). Le refresh graphique est super gourmand.

Bon courage.
2
dodo7263 Messages postés 614 Date d'inscription mercredi 10 septembre 2008 Statut Membre Dernière intervention 9 février 2017 6
6 sept. 2013 à 18:23
Salut,

Je rejoins basicInstinct...
si c'est du xlsx passe par openXML.
J'ai ouvert un fil de discussion sur un problème pour lequel j'ai trouve la solution. C'est un exemple pour écrire dans un document word mais le principe est la.
C'est ici : http://codes-sources.commentcamarche.net/forum/affich-10001277-openxml-word-2010-2007-comportement-different#p10001574
0
warzet Messages postés 44 Date d'inscription lundi 27 août 2007 Statut Membre Dernière intervention 1 novembre 2016
26 août 2013 à 17:17
J'ai fait expressément abstraction des déclarations et autre pour me concentrer sur le vif du sujet. alors saches que c'est code C" et non vb, alors si tu as une autre proposition, je suis à ton écoute. D'autre part, saches ce code fonctionne parfaitement, mais, il met beaucoup de temps pour tout exécuter et je souhaiterais le rendre rapide. Merci pour tout.
0
geeegeee Messages postés 118 Date d'inscription samedi 6 octobre 2012 Statut Membre Dernière intervention 17 mars 2014
26 août 2013 à 10:14
Bnojour,

il faut tout d'abors ajoutter la reference Microsoft Excel comme suivant :
projet + ajouter une refenece +Menu COM +valider OK
Code :

imports Microsoft.Excel....

Class Form1

sub button1_Click()

Dim c,n as inetger
Dim xl as new Excel.application

xl.visible=true
xl.worckboxs.add

for c=0 to Datagridview1.columns.count-1
xl.cells(c+1,1)=Datagridview1.columns(c).name
next

for l as integer=0 to Datagridview1.rows.count-1
for c=0 to Datagridview1.rows.count-1
xl.cells(l+1,j+1)=Datagridview1.rows(l).cells(c).value
next c
next l

end sub
eh bonne chance
next

Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop


Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim c, ligne As Integer
Dim xl As New Excel.Application

xl.Visible = True
xl.Workbooks.Add()

Try
For ligne = 0 To DataGridView1.RowCount - 1
For c = 0 To DataGridView1.ColumnCount - 1
xl.Cells(1, c + 1) = DataGridView1.Columns(c).HeaderText
xl.Cells(ligne + 2, c + 1) = DataGridView1.Rows(ligne).Cells(c).Value
Next c
Next ligne

Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

End Class
-1
Rejoignez-nous