Impression de fichiers word/excel

Contenu du snippet

Ma librairie pour les programmes de gestion :

- Impression d'un fichier word simple ; paramêtres : chemin du fichier, booleen qui ouvre word ou non, nombre de copies.
- Impression d'un fichier word avec signets ; paramêtres : les mêmes que précédants + 3 tableaux (Liste des signets du fichier word, liste des valeurs à mettre dans les signets, nombre de caractères pour les valeurs)
- Remplissage d'un fichier excel à partir d'un datagridview ; paramêtres : un datagridview, chemin du fichier excel, chaine "titre de l'impression". Excel possédant moins de couleur qu'un datagridview, c'est la composante principale de la couleur qui est transférée.
- Ouverture d'un fichier Word ; paramêtre : chemin du fichier
- Ouverture d'un fichier Excel ; paramêtre : chemin du fichier
- Transformation d'un nombre décimal en chaine de caractère, arrondi à 2 chiffres après la virgule (0 inclus), pratique pour l'impression de facture ; paramêtres : double

Source / Exemple :


class MesOutils
    {
        public MesOutils()
        {
        }
   
     public void ImprimerFichierWord(object fileName, Boolean visible, int NbCopies)
        {
            try
            {
                Microsoft.Office.Interop.Word._Application aWord;
                Microsoft.Office.Interop.Word._Document aDoc;
                aWord = new Microsoft.Office.Interop.Word.Application();
                aWord.Visible = visible;
                object Missing = System.Reflection.Missing.Value;
                aDoc = aWord.Documents.Open(ref fileName, ref Missing, ref Missing, ref Missing, ref  Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing);//, ref Missing);
                object myTrue = true;
                object myFalse = false;
                object missingValue = Type.Missing;
                object range = Microsoft.Office.Interop.Word.WdPrintOutRange.wdPrintAllDocument;
                object items = Microsoft.Office.Interop.Word.WdPrintOutItem.wdPrintDocumentContent;
                object copies = NbCopies;
                object pages = "1";
                object pageType = Microsoft.Office.Interop.Word.WdPrintOutPages.wdPrintAllPages;
                aDoc.PrintOut(ref myFalse, ref myFalse, ref range,
                    ref missingValue, ref missingValue, ref missingValue,
                    ref items, ref copies, ref pages, ref pageType, ref myFalse,
                    ref myTrue, ref missingValue, ref myFalse, ref missingValue,
                    ref missingValue, ref missingValue, ref missingValue);
                aWord.Quit(ref myFalse, ref missingValue, ref missingValue);
                aWord = null;
                aDoc = null;
            }
            catch { MessageBox.Show("Erreur lors de l'ouverture du document"); }
        }

        public void ImprimerWord(string Document, Boolean WordVisible, int NbCopies, ArrayList Valeurs, ArrayList Signets, ArrayList NbCaracteres)
        {
            try
            {
                if (Signets.Count == Valeurs.Count) //S'il y a autant de signet que de valeurs à y écrire
                {
                    Microsoft.Office.Interop.Word._Application aWord;
                    Microsoft.Office.Interop.Word._Document aDoc;
                    aWord = new Microsoft.Office.Interop.Word.Application();
                    aWord.Visible = WordVisible; //Word n'apparait pas
                    object Missing = System.Reflection.Missing.Value;
                    object FileName = Document;
                    aDoc = aWord.Documents.Open(ref FileName, ref Missing, ref Missing, ref Missing, ref  Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing);
                    object myTrue = true;
                    object myFalse = false;
                    object missingValue = Type.Missing;
                    object range = Microsoft.Office.Interop.Word.WdPrintOutRange.wdPrintAllDocument;
                    object items = Microsoft.Office.Interop.Word.WdPrintOutItem.wdPrintDocumentContent;
                    object copies = NbCopies;
                    object pages = NbCopies.ToString();
                    object pageType = Microsoft.Office.Interop.Word.WdPrintOutPages.wdPrintAllPages;

                    Hashtable Bks = new Hashtable();
                    for (int i = 1; i <= aDoc.Bookmarks.Count; i++)
                    {
                        object index = i;
                        Microsoft.Office.Interop.Word.Bookmark bk = aDoc.Bookmarks.get_Item(ref index);
                        Bks.Add(bk.Name, bk.Range);
                    }
                    for (int i = 0; i < Signets.Count; i++)
                    {
                        ((Microsoft.Office.Interop.Word.Range)Bks[Signets[i].ToString()]).Text = new String(Valeurs[i].ToString().ToCharArray()).PadRight(System.Convert.ToInt32(NbCaracteres[i]), '_');
                        ((Microsoft.Office.Interop.Word.Range)Bks[Signets[i].ToString()]).Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineSingle;
                    }
                    aDoc.PrintOut(ref myFalse, ref myFalse, ref range,
                        ref missingValue, ref missingValue, ref missingValue,
                        ref items, ref copies, ref pages, ref pageType, ref myFalse,
                        ref myTrue, ref missingValue, ref myFalse, ref missingValue,
                        ref missingValue, ref missingValue, ref missingValue);
                    aWord = null;
                    aDoc = null;
                }
            }
            catch { MessageBox.Show("Erreur lors de l'ouverture du document ..."); }
        }

        public void VoirFichierWord(object fileName)
        {
            try
            {
                Microsoft.Office.Interop.Word._Application aWord;
                Microsoft.Office.Interop.Word._Document aDoc;
                aWord = new Microsoft.Office.Interop.Word.Application();
                aWord.Visible = true;
                object Missing = System.Reflection.Missing.Value;
                aDoc = aWord.Documents.Open(ref fileName, ref Missing, ref Missing, ref Missing, ref  Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing);//, ref Missing);
                aWord = null;
                aDoc = null;
            }
            catch { MessageBox.Show("Erreur lors de l'ouverture du document"); }
        }

        public void VoirFichierExcel(string fileName)
        {
            try
            {

                object Missing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Excel._Application xlApp;
                Microsoft.Office.Interop.Excel._Workbook xlClasseur;
                Microsoft.Office.Interop.Excel._Worksheet xlFeuill1;
                xlApp = new Microsoft.Office.Interop.Excel.Application();
                xlApp.Visible = true;
                xlClasseur = xlApp.Workbooks.Open(fileName,
                    Missing, Missing, Missing, Missing,
                    Missing, Missing, Missing, Missing,
                    Missing, Missing, Missing, Missing,
                    Missing, Missing);
                Microsoft.Office.Interop.Excel.Sheets xlFeuilles = xlClasseur.Sheets;
                xlFeuill1 = (Microsoft.Office.Interop.Excel._Worksheet)xlFeuilles["Feuil1"];
            }
            catch { MessageBox.Show("Erreur de l'ouverture du document"); }
        }

        public void Impression(string Titre, DataGridView Data)
        {
            try
            {
                //UseWaitCursor = true;
                object Missing = System.Reflection.Missing.Value;
                String fileName = new ConfigForm().getCheminDOCS() + "Vierge.xls";
                Microsoft.Office.Interop.Excel._Application xlApp;
                Microsoft.Office.Interop.Excel._Workbook xlClasseur;
                Microsoft.Office.Interop.Excel._Worksheet xlFeuill;

                xlApp = new Microsoft.Office.Interop.Excel.Application();
                xlApp.Visible = true;
                xlClasseur = xlApp.Workbooks.Open(fileName,
                    Missing, Missing, Missing, Missing,
                    Missing, Missing, Missing, Missing,
                    Missing, Missing, Missing, Missing,
                    Missing, Missing);
                Microsoft.Office.Interop.Excel.Sheets xlFeuilles = xlClasseur.Sheets;
                xlFeuill = (Microsoft.Office.Interop.Excel._Worksheet)xlFeuilles["A"];
                Microsoft.Office.Interop.Excel.Range r;
                r = xlFeuill.get_Range("A1", Missing);
                r.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, Titre.ToString());
                r = xlFeuill.get_Range("A2", Missing);
                r.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, "Imprimé le " + DateTime.Now.ToString().Substring(0, 10));

                int ligne = 6;
                int Cl = 0;
                string champ = "";
                //.Affichage des noms de colonne
                foreach (DataGridViewColumn clm in Data.Columns)
                {
                    if (clm.Visible)
                    {
                        champ = LettreFromIndice(Cl) + "4";
                        r = xlFeuill.get_Range(champ, Missing);
                        r.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, clm.HeaderText.ToString());
                        Cl++;
                    }
                }
                //.Remplissage des lignes
                foreach (DataGridViewRow dr in Data.Rows)
                {
                    try
                    {
                        for (int j = 0; j < Data.ColumnCount; j++)
                        {
                            champ = LettreFromIndice(j) + ligne.ToString();
                            r = xlFeuill.get_Range(champ, Missing);
                            try
                            {
                                r.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, dr.Cells[j].Value.ToString());
                                //MessageBox.Show(dr.Cells[j].Style.BackColor.ToArgb().ToString());
                                r.Interior.ColorIndex = this.getCouleurExcel(System.Convert.ToInt32(dr.Cells[j].Style.BackColor.R), System.Convert.ToInt32(dr.Cells[j].Style.BackColor.G), System.Convert.ToInt32(dr.Cells[j].Style.BackColor.B));
                                //r.Font.FontStyle = Color.FromName(dr.Cells[j].Style.Font.Style.ToString());
                            }
                            catch
                            {
                                if (System.Convert.ToBoolean(dr.Cells[j]))
                                    r.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, "Oui");
                                else
                                    r.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, "Non");
                            }
                        }
                    }
                    catch { }
                    ligne++;
                }
                //xlFeuill.Columns.Width
                //UseWaitCursor = false;
            }
            catch { MessageBox.Show("Impossible d'ouvrir le document Excel type : Vierge.xls"); }
        }
        public int getCouleurExcel(int R, int G, int B)
        {
            if (R == 0 && G == 0 && B == 0)
                return 2;
            else if (R > G && R > B)
                return 3;
            else if (G > B)
                return 4;
            else return 5;
        }
        private string LettreFromIndice(int Indice)
        {
            if (Indice < 26)
                return ((char)(65 + Indice)).ToString();
            else return ""; //A faire
        }

        public string ArrondirToString(double D)
        {
            //Arrondi un double avec 2 chiffres après la virgule
            string Double = D.ToString();
            string A = "", B = "";
            try
            {
                //Si il y a une virgule, on stocke la partie entière dans A
                A = Double.Substring(0, Double.IndexOf(","));
                B = Double.Substring(Double.IndexOf(",") + 1, Double.Length - 1 - Double.IndexOf(","));
            }
            catch
            {
                //Sinon on retourne la partie entière suivie de ",00"
                return Double + ",00";
            }
            if (B.Length == 1) //Si 1 chiffre après la virgule
                return Double + "0";
            else if (B.Length == 2) //Si 2 chiffres après la virgule
                return Double;
            else if (System.Convert.ToInt32(B.Substring(2, 1)) < 5) //Si le 3eme chiffre après la virgule <5
                return A + "," + B.Substring(0, 2);
            else if (System.Convert.ToInt32(B.Substring(2, 1)) >= 5) //Si le 3eme chiffre après la virgule >=5
            {
                if (System.Convert.ToInt32(B.Substring(0, 2)) == 99) //Si A,99
                    return (System.Convert.ToInt32(A) + 1).ToString() + ",00";
                else if (System.Convert.ToInt32(B.Substring(1, 1)) == 9) //Si A,X9
                    return A + "," + (System.Convert.ToInt32(B.Substring(0, 1)) + 1).ToString() + "0";
                else return A + "," + B.Substring(0, 1) + (System.Convert.ToInt32(B.Substring(1, 1)) + 1).ToString();
            }
            return "0,00"; //Impossible
        }
}

Conclusion :


Améliorations à faire :
Pour la fonction qui reproduit un datagridview dans un fichier Excel, il faudrait que les "font" soient reproduits aussi.
De plus ce système est limité à 26 colonnes (Z).

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.