Formatage d'un nombre en c#

Résolu
dhago - 13 juil. 2015 à 13:23
 dhago - 21 juil. 2015 à 10:22
Bonjour,

Dans mon stage, je travaille sur l'automatisation office en c# et je suis un grand debutant en programmation.
je suis bloqué depuis deux jours sur ce problème suivant. S'il y'a une ame charitable qui peut m'aider, je vous serais reconnaissant

Je souhaite formater un nombre (ex: 4238975,6852) suivant des règles prédefini par l'utilisateur.

J'ai le keyword <AMOUNT><FORMAT_S1TD0C2> dans un fichier word."S1TD0C2" étant la règle.

Je dois tester s'il y'a "<FORMAT" après <AMOUNT>.

Ensuite recupérer le keyword (règle) juste après le underscore (cad S1TD0C2) afin d'appliquer la règle sur le nombre.

Explication de la règle:

S1: met un signe + devant le nombre
T: mettre un separateur des milliers
D0:correspond le nombre de 0 devant le nombre

Merci pour votre aide

4 réponses

cgandco Messages postés 219 Date d'inscription mercredi 26 octobre 2011 Statut Membre Dernière intervention 22 juin 2017 9
14 juil. 2015 à 11:42
Bonjour,

voila déja un code pour la récup du format,


                object toFind = "<AMOUNT>";
                object endFind = "<";
                object strToReplace = "";
                String theFormat = "";
                if (wordApp.Selection.Find.Execute(ref toFind, 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)) {
                    var pos = wordApp.Selection.MoveEndUntil(ref endFind, ref missing);
                    if (pos>0) {
                        var toDeleteBefore = wordApp.Selection.Text;
                        endFind = ">";
                        pos = wordApp.Selection.MoveEndUntil(ref endFind, ref missing);
                        if (pos > 0) {
                             theFormat = wordApp.Selection.Text;
                            strToReplace = theFormat + ">";
                            theFormat = theFormat.Substring(toDeleteBefore.Length+1);
                            if (theFormat.Substring(0,7).ToUpper() == "FORMAT_") {
                                theFormat = theFormat.Substring(7);
                            }
                            else {
                                strToReplace = "";
                            }
                        }
                    }
                }




pour la suite, si j'ai le temps ce soir.

bonne journée

2
Merci énormement @cgandco.
ça m'a permit de récuper la règle en question.
pour le reste je vous attendrai impatiemment
Merci encore
0
cgandco Messages postés 219 Date d'inscription mercredi 26 octobre 2011 Statut Membre Dernière intervention 22 juin 2017 9 > dhago
14 juil. 2015 à 12:25
pour ce soir,

la règle a t'elle une longueur fixe ou pas ?

c à d est-ce que S T D et C existent toujours ?
0
Je vous donne un peu plus de détails:

Sx: dont S1 signifie SIGNED (le signe sera affiché) et S0 (le signe ne sera pas affiché)
Tc: dont c correspond au caractère séparateur des milliers (T0 signifie pas de séparateur).
Dx: pour remplir x 0 (zéros) non significatif devant le nombre
Cx: dont x est le nombre de chiffre après la virgule

Par exemple:
<AMOUNT><FORMAT_S1TcD0C2> +1 256 898.16

Concernant la règle, l'utilisateur peut predefinir par exemple:
S0T0D1C6, S1T0D3C4....etc.

Donc, si je repond à votre question. S, T, D et C existent bien toujours.
Merci pour le temps que vous me consacrez !
0
cgandco Messages postés 219 Date d'inscription mercredi 26 octobre 2011 Statut Membre Dernière intervention 22 juin 2017 9 > dhago
15 juil. 2015 à 14:05
Bonjour,

voila ce que j'ai codé (il y a surement moyen de refactoriser et de placer des traitements d'erreur, mais bon):

        private void CreateWordDocument(object fileName,
                                        object saveAs) {
            //Set Missing Value parameter - used to represent
            // a missing value when calling methods through
            // interop.
            object missing = System.Reflection.Missing.Value;

            //Setup the Word.Application class.
            Word.Application wordApp =
                new Word.Application() {
                    Visible = true
                };

            //Setup our Word.Document class we'll use.
            Word.Document aDoc = null;

            // Check to see that file exists
            if (File.Exists((string)fileName)) {
                DateTime today = DateTime.Now;

                object readOnly = false;
                object isVisible = true;

                //Set Word to be not visible.
                //wordApp.Visible = false;

                //Open the word document
                aDoc = wordApp.Documents.Open(ref fileName, ref missing,
                    ref readOnly, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref isVisible, ref missing, ref missing,
                    ref missing, ref missing);

                // Activate the document
                aDoc.Activate();

                object toFind = "<AMOUNT>";
                object endFind = "<";
                object strToReplace = "";
                String theFormat = "";
                if (wordApp.Selection.Find.Execute(ref toFind, 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)) {
                    var pos = wordApp.Selection.MoveEndUntil(ref endFind, ref missing);
                    if (pos > 0) {
                        var toDeleteBefore = wordApp.Selection.Text;
                        endFind = ">";
                        pos = wordApp.Selection.MoveEndUntil(ref endFind, ref missing);
                        if (pos > 0) {
                            theFormat = wordApp.Selection.Text;
                            strToReplace = theFormat + ">";
                            theFormat = theFormat.Substring(toDeleteBefore.Length + 1);
                            if (theFormat.Substring(0, 7).ToUpper() == "FORMAT_") {
                                theFormat = theFormat.Substring(7);
                            }
                            else {
                                strToReplace = "";
                            }
                        }
                    }
                }



                double amount = 1256898.1625;
                object theOne = Word.WdReplace.wdReplaceOne;
                //formatage de "amount"
                if (!String.IsNullOrEmpty((String)strToReplace)) {
                    object Theammount = FormatWord(theFormat, amount);
                    wordApp.Selection.MoveEnd(missing, 1);
                    
                    if (wordApp.Selection.Text == (String)strToReplace) {
                        wordApp.Selection.Text = (String)Theammount;
                    }


                }

            }
            else {
                MessageBox.Show("File dose not exist.");
                return;
            }

            //Save the document as the correct file name.
            aDoc.SaveAs(ref saveAs, 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);

            //Close the document - you have to do this.
            aDoc.Close(ref missing, ref missing, ref missing);

            MessageBox.Show("File created.");
        }

        private String FormatWord(String theFormat, Double valeur) {
            Boolean withSigne = false;
            int pos = theFormat.IndexOf("S");
            if (pos > -1 && pos < theFormat.Length - 1) {
                if (theFormat.Substring(pos + 1, 1) == "1") {
                    withSigne = true;
                }
            }

            //détection du separateur
            Boolean withSeparator = false;
            String Separator = "";
            pos = theFormat.IndexOf("T");
            if (pos > -1 && pos < theFormat.Length - 1) {
                Separator = theFormat.Substring(pos + 1, 1);
                if (Separator != "0") {
                    withSeparator = true;
                }
            }

            //detection du lnombre de chiffre devant la virgule
            String LeadStr = "##";
            int LeadNumber = 0;
            Char chrEntier = '#';
            pos = theFormat.IndexOf("D");
            if (pos > -1 && pos < theFormat.Length - 1) {
                LeadStr = theFormat.Substring(pos + 1, 1);
                if (int.TryParse(LeadStr, out LeadNumber) && LeadNumber != 0) {
                    if (LeadNumber == 1) {
                        LeadStr = "#0";
                    }
                    else {
                        chrEntier = '0';
                        LeadStr = new string(chrEntier, LeadNumber);
                    }
                }
            }

            //detection du nombre de decimale
            String DecimalStr = ".#########";
            int DecimalNumber = 0;
            pos = theFormat.IndexOf("C");
            if (pos > -1 && pos < theFormat.Length - 1) {
                DecimalStr = theFormat.Substring(pos + 1, 1);
                if (int.TryParse(DecimalStr, out DecimalNumber) && DecimalNumber != 0) {
                    DecimalStr = new string('0', DecimalNumber);
                    DecimalStr = "." + DecimalStr;
                }
            }

            String fmt = "";

            // si on a un separateur placer une virgule avant le premier chiffre devant la virgule
            if (withSeparator) {
                LeadStr = LeadStr.Substring(0, LeadStr.Length - 1) + "," + LeadStr.Substring(LeadStr.Length - 1);
            }

            //on assemble le format
            fmt = LeadStr + DecimalStr;

            //si signe alors on triple le format
            if (withSigne) {
                fmt = "+" + fmt + ";-" + fmt + ";" + fmt;
            }

            // On Clone la culture
            CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();

            //on la modifie
            if (withSeparator) {
                ci.NumberFormat.NumberGroupSeparator = Separator;
                if (Separator == ",") {
                    ci.NumberFormat.NumberDecimalSeparator = ".";
                }
                if (Separator == ".") {
                    ci.NumberFormat.NumberDecimalSeparator = ",";
                }
            }

            //On l'applique au format et données
            return String.Format(ci, String.Format("{{0:{0}}}", fmt), valeur);

        }




il te faut aussi

using System.Globalization;



Bonne journée
0
Bonjour,

Je suis sous le choc ! Vous avez fait un travail formidable. Honnetement, je ne pensais pas qu'il y'avait des gens qui peuvent donner autant leur temps précieux. Je suis étonné mais je vous remercie énormement @cgandco. :)
0
Whismeril Messages postés 19028 Date d'inscription mardi 11 mars 2003 Statut Non membre Dernière intervention 24 avril 2024 656
13 juil. 2015 à 13:42
Bonjour, pour trouver tes mots clés Amount et Format, tu peux utiliser une Regex.
Voir cette source très utile
http://codes-sources.commentcamarche.net/source/41969-tester-et-compiler-de-regex-sauvegarde-gestion-des-regex-en-xml

Pour formater tes nombres, regarde double.ToString() ou éventuellement string.Format().

0
cgandco Messages postés 219 Date d'inscription mercredi 26 octobre 2011 Statut Membre Dernière intervention 22 juin 2017 9
13 juil. 2015 à 13:47
Bonjour,

si tu es bloqué depuis deux jours,

peux tu nous donner au moins le code de découpe qui te donne des problèmes.

et dans tes rêgles, le C2 ???, et le format sans séparateur de millier ??? , ...

bonne journée.


0
Ré-bonjour,

Merci pour votre rapidité @whismeril et @cgandco.
voici les regles corrigées:

S1: le signe sera affiché
S0: le signe ne sera pas affiché
Tc: mettre un separateur des milliers
T0: pas de séparateur des milliers
D0:correspond le nombre de 0 devant le nombre
Cx: x est le nombre de chiffre après la virgule.

Voici mon code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Word = Microsoft.Office.Interop.Word;



namespace formatage
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

    private void CreateWordDocument(object fileName,
                                        object saveAs)
        {
            //Set Missing Value parameter - used to represent
            // a missing value when calling methods through
            // interop.
            object missing = System.Reflection.Missing.Value;

            //Setup the Word.Application class.
            Word.Application wordApp =
                new Word.Application();

            //Setup our Word.Document class we'll use.
            Word.Document aDoc = null;

            // Check to see that file exists
            if (File.Exists((string)fileName))
            {
                DateTime today = DateTime.Now;

                object readOnly = false;
                object isVisible = false;

                //Set Word to be not visible.
                wordApp.Visible = false;

                //Open the word document
                aDoc = wordApp.Documents.Open(ref fileName, ref missing,
                    ref readOnly, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref isVisible, ref missing, ref missing,
                    ref missing, ref missing);

                // Activate the document
                aDoc.Activate();


               double amount = 1256898.1625;
                
             //formatage de "amount"

               
            }
            else
            {
                MessageBox.Show("File dose not exist.");
                return;
            }

            //Save the document as the correct file name.
            aDoc.SaveAs(ref saveAs, 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);

            //Close the document - you have to do this.
            aDoc.Close(ref missing, ref missing, ref missing);

            MessageBox.Show("File created.");
        }


//Ensuite, j'appelle la méthode comme suit:

private void button1_Click(object sender, EventArgs e)
        {
           CreateWordDocument(@"C:\temp\AvantFormatage.doc",
                                @"C:\temp\ResultatFormatage.doc");
        }


   }
}


0
Rejoignez-nous