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

Windows Forms Discussion :

Générer un fichier Excel à partir d'un dataset


Sujet :

Windows Forms

  1. #1
    Membre du Club
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mars 2017
    Messages
    176
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Conseil

    Informations forums :
    Inscription : Mars 2017
    Messages : 176
    Points : 58
    Points
    58
    Par défaut Générer un fichier Excel à partir d'un dataset
    Bonjour,

    Je voudrais savoir comment je pourrais optimiser ce code car ça me prend à peu près 1 heure et demi pour générer un fichier Excel. Je ne partage que 2 fonctions (getAllEmployeesList, getAllEmployeesOrderList) mais il y en a 4 en tout. Chaque fonction correspond à un onglet du fichier excel. Chaque fonction retourne 2000 lignes environ.

    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
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
            private void ExportDataSetToExcel(DataSet dataset, string path)
            {
                int inHeaderLength = 0, inColumn = 0, inRow = 0;
                System.Reflection.Missing Default = System.Reflection.Missing.Value;
     
                path = "...";
     
                OfficeExcel.Application eApp = new OfficeExcel.Application();
                OfficeExcel.Workbook ewbook = eApp.Workbooks.Add(1);
                foreach (DataTable dt in dataset.Tables)
                {
                    OfficeExcel.Worksheet sheet = ewbook.Sheets.Add(Default, ewbook.Sheets[ewbook.Sheets.Count], 1, Default);
                    sheet.Name = dt.TableName;
     
                    for (int i = 0; i < dt.Columns.Count; i++)
                        sheet.Cells[inHeaderLength + 1, i + 1] = dt.Columns[i].ColumnName;
     
                    sheet.Columns.AutoFit();
     
                    for (int m = 0; m < dt.Rows.Count; m++)
                    {
                        for (int n = 0; n < dt.Columns.Count; n++)
                        {
                            inColumn = n + 1;
                            inRow = inHeaderLength + 2 + m;
                            sheet.Cells[inRow, inColumn] = dt.Rows[m].ItemArray[n].ToString();
                            if (m % 2 == 0)
                                sheet.Cells[inRow, inColumn].Interior.Color = System.Drawing.ColorTranslator.FromHtml("#D9E1F2");
     
                            sheet.Cells[1, inColumn].Interior.Color = System.Drawing.ColorTranslator.FromHtml("#1F80C1");
                            sheet.Cells[1, inColumn].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
                            sheet.Cells[1, inColumn].Font.Bold = true;
     
                            Microsoft.Office.Interop.Excel.Range firstRow = (Microsoft.Office.Interop.Excel.Range)sheet.Rows[1];
                            firstRow.AutoFilter(1,
                                                Type.Missing,
                                                Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlAnd,
                                                Type.Missing,
                                                true);
                        }
                    }
     
                    sheet.UsedRange.Columns.AutoFit();
                }
     
                eApp.DisplayAlerts = false;
                Microsoft.Office.Interop.Excel.Worksheet lastWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ewbook.Worksheets[1];
                lastWorkSheet.Delete();
                eApp.DisplayAlerts = true;
     
                (ewbook.Sheets[1] as OfficeExcel._Worksheet).Activate();
     
                ewbook.SaveAs(path, Default, Default, Default, false, Default, OfficeExcel.XlSaveAsAccessMode.xlNoChange, Default, Default, Default, Default, Default);
                ewbook.Close();
                eApp.Quit();
     
     
                System.Diagnostics.Process.Start(path);
            }
     
     
            private DataTable getAllEmployeesList()
            {
                string constr = ConfigurationManager.ConnectionStrings["constr527"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM Test1"))
                    {
                        using (SqlDataAdapter da = new SqlDataAdapter())
                        {
                            DataTable dt = new DataTable();
                            cmd.CommandType = CommandType.Text;
                            cmd.Connection = con;
                            da.SelectCommand = cmd;
                            da.Fill(dt);
                            return dt;
                        }
                    }
                }
            }
     
            private DataTable getAllEmployeesOrderList()
            {
                string constr = ConfigurationManager.ConnectionStrings["constr527"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM Test2"))
                    {
                        using (SqlDataAdapter da = new SqlDataAdapter())
                        {
                            DataTable dt = new DataTable();
                            cmd.CommandType = CommandType.Text;
                            cmd.Connection = con;
                            da.SelectCommand = cmd;
                            da.Fill(dt);
                            return dt;
                        }
                    }
                }
            }
     
            private DataSet getDataSetExportToExcel()
            {
                DataSet ds = new DataSet();
                DataTable dtEmp = new DataTable("Test1");
                dtEmp = getAllEmployeesList();
     
                DataTable dtEmpOrder = new DataTable("Test2");
                dtEmpOrder = getAllEmployeesOrderList();
                ds.Tables.Add(dtEmp);
                ds.Tables.Add(dtEmpOrder);
                return ds;
            }
    Merci

  2. #2
    Membre éclairé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Août 2010
    Messages
    479
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2010
    Messages : 479
    Points : 762
    Points
    762
    Par défaut
    Salut, c'est avec l'interop que tu créés ton doc Excel ?
    Si c'est le cas ne cherche pas plus loin c'est ça qui est lent... Tu trouveras sur le net des biblio qui te génèreront un excel sans passer par l'application Excel. Gratuit et payant existent je pense.

  3. #3
    Membre du Club
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mars 2017
    Messages
    176
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Conseil

    Informations forums :
    Inscription : Mars 2017
    Messages : 176
    Points : 58
    Points
    58
    Par défaut
    Bonjour,

    Oui c'est interop que j'utilise.

    Merci

  4. #4
    Membre du Club
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mars 2017
    Messages
    176
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Conseil

    Informations forums :
    Inscription : Mars 2017
    Messages : 176
    Points : 58
    Points
    58
    Par défaut
    En utilisant la librairie ClosedXML.Excel ça prend 3 secondes au lieu d'une heure et demi avec Interop

    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
    private void ExportToExcel()
    {
    	DataTable dt1 = getAllEmployeesList();
    	DataTable dt2 = getAllEmployeesOrderList();
     
    	List<DataTable> dts = new List<DataTable>();
    	dts.Add(dt1);
    	dts.Add(dt2);
     
    	using (XLWorkbook wb = new XLWorkbook())
    	{
    		for (int i = 0; i < dts.Count; i++)
    		{
    			wb.Worksheets.Add(dts[i]);
    		}
     
    		wb.SaveAs(sPath);
     
    		System.Diagnostics.Process.Start(sPath);
    	}
    }

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Générer un fichier excel à partir de critères
    Par samiroff_ice dans le forum Général Conception Web
    Réponses: 0
    Dernier message: 27/03/2016, 19h18
  2. [Excel] Générer un fichier excel à partir d'une table mysql + symfony 2
    Par Jerniti dans le forum Bibliothèques et frameworks
    Réponses: 0
    Dernier message: 23/05/2013, 12h33
  3. Réponses: 2
    Dernier message: 19/07/2011, 10h53
  4. [REPORTS 6i] Générer un fichier excel à partir de reports
    Par moneyinthebank dans le forum Reports
    Réponses: 7
    Dernier message: 07/03/2007, 14h13
  5. Réponses: 4
    Dernier message: 02/05/2005, 20h25

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