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

VC++ .NET Discussion :

Extraction attribut autocad vers Excel


Sujet :

VC++ .NET

  1. #1
    Invité
    Invité(e)
    Par défaut Extraction attribut autocad vers Excel
    Bonjour,

    Tout d’abord je tiens à préciser que je suis débutant en terme de programmation sur visual basic.

    Je souhaiterai modifier le programme (voir fichiers classes ci jointes) afin d'exporter mes attribut dans la feuille 2 d'un fichier excel existant (sans écraser les données des autres feuilles).
    Actuellement le programme enregistre les données extraites dans un nouveau fichier xls (si le nom du fichier n'existe pas) ou écrase le fichier (si le nom du fichier existe déjà).

    Le but serai d'exporter les attributs dans la feuil2 d'un fichier .xls existant afin d'avoir de garder les formules dans la feuil1 (formules en liaison avec feuil2)

    Code de la class "command"
    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
     
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading;
    using Autodesk.AutoCAD.ApplicationServices;
    using Autodesk.AutoCAD.DatabaseServices;
    using Autodesk.AutoCAD.EditorInput;
    using Autodesk.AutoCAD.Runtime;
    using Autodesk.AutoCAD.Windows;
    using ExcelLateBinding;
    using AcAp = Autodesk.AutoCAD.ApplicationServices.Application;
     
    namespace ExcelAttribute
    {
        public class Commands
        {
            private string _expMsg, _dispMsg, _impMsg;
            private bool _fr = Thread.CurrentThread.CurrentCulture.Name.StartsWith("fr");
            private Database _db = HostApplicationServices.WorkingDatabase;
            private Editor _ed = AcAp.DocumentManager.MdiActiveDocument.Editor;
     
            public Commands()
            {
                _expMsg = _fr ? "Extraction d'attributs" : "Attributes Extract";
                _dispMsg = _fr ? "Ouvrir le fichier Excel ?" : "Open Excel file ?";
                _impMsg = _fr ? "Importation d'attributs" : "Attributes Import";
            }
     
            [CommandMethod("EATT", CommandFlags.UsePickSet)]
            public void ExportAttributes()
            {
                TypedValue[] filter = new TypedValue[2] { new TypedValue(0, "INSERT"), new TypedValue(66, 1) };
                PromptSelectionResult psr = _ed.GetSelection(new SelectionFilter(filter));
                if (psr.Status != PromptStatus.OK) return;
     
                string path = (string)AcAp.GetSystemVariable("DWGNAME");
                path = string.Format("{0}{1}.xls", AcAp.GetSystemVariable("DWGPREFIX"), path.Substring(0, path.LastIndexOf('.')));
                SaveFileDialog dlg = new SaveFileDialog(_expMsg, path, "xls;xlsx", "", 0);
                if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
                string filename = dlg.Filename;
     
                System.Data.DataTable table = new System.Data.DataTable();
                table.Columns.Add("HANDLE", typeof(String));
                table.Columns.Add("NOM", typeof(String));
                using (Transaction tr = _db.TransactionManager.StartTransaction())
                {
                    foreach (SelectedObject so in psr.Value)
                    {
                        BlockReference br = tr.GetObject(so.ObjectId, OpenMode.ForRead) as BlockReference;
                        BlockTableRecord btr = br.IsDynamicBlock ?
                            (BlockTableRecord)tr.GetObject(br.DynamicBlockTableRecord, OpenMode.ForRead) :
                            (BlockTableRecord)tr.GetObject(br.BlockTableRecord, OpenMode.ForRead);
                        table.Rows.Add(new string[2] { br.Handle.ToString(), btr.Name });
                        foreach (KeyValuePair<string, string> pair in GetAttributes(br, tr))
                        {
                            if (!table.Columns.Contains(pair.Key))
                                table.Columns.Add(pair.Key, typeof(String));
                            table.Rows[table.Rows.Count - 1][pair.Key] = pair.Value;
                        }
                    }
                }
                ExcelWriter xlw = new ExcelWriter();
                try
                {
                    xlw.Open(filename);
                    if (File.Exists(filename))
                        xlw.Clear();
                    object columns = LateBindings.Get(xlw.Worksheet, "Columns");
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        xlw.Write(table.Columns[i].ColumnName);
                    }
                    xlw.NewLine();
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        xlw.WriteLine(table.Rows[i].ItemArray);
                    }
                    LateBindings.Invoke(columns, "AutoFit");
                    xlw.Save();
                    if (System.Windows.Forms.MessageBox.Show(
                        _dispMsg,
                        _expMsg,
                        System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        LateBindings.Set(xlw.Application, "DisplayAlerts", true);
                        LateBindings.Set(xlw.Application, "Visible", true);
                        LateBindings.Set(xlw.Application, "UserControl", true);
                    }
                    else
                    {
                        xlw.Close();
                    }
                }
                catch (System.Exception e)
                {
                    xlw.Close();
                    _ed.WriteMessage("\n{0}\n{1}", e.Message, e.StackTrace);
                }
            }
    Code de la class "excelWriter"
    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
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
     
    using System;
    using System.IO;
     
    namespace ExcelLateBinding
    {
        public class ExcelWriter
        {
            // Champs
            private object m_Application;
            private object m_Workbook;
            private object m_Worksheet;
            private object _mis = Type.Missing;
            private int m_ColumnCount;
            private int m_ColumnIndex;
            private int m_RowCount;
            private int m_RowIndex;
            private bool m_StreamEnded;
            private string m_filename;
     
            // Constructeur
            public ExcelWriter()
            {
                m_StreamEnded = false;
                m_ColumnCount = -1;
                m_ColumnIndex = -1;
                m_RowCount = -1;
                m_RowIndex = -1;
            }
     
            // Propriétés
     
            public object Application
            {
                get { return m_Application; }
            }
     
            public object Workbook
            {
                get { return m_Workbook; }
            }
     
            public object Worksheet
            {
                get { return m_Worksheet; }
            }
     
            public bool StreamEnded
            {
                get { return m_StreamEnded; }
            }
     
            public string Version
            {
                get { return (string)LateBindings.Get(m_Application, "Version"); }
            }
     
            // Méthodes
     
            // Ferme le processus Excel
            public void Close()
            {
                if (m_Workbook != null)
                {
                    LateBindings.Invoke(m_Workbook, "Close", new object[3] { false, _mis, _mis });
                    m_Workbook = null;
                }
                if (m_Application != null)
                {
                    LateBindings.Set(m_Application, "DisplayAlerts", true);
                    LateBindings.Invoke(m_Application, "Quit");
                    LateBindings.ReleaseInstance(m_Application);
                    m_Application = null;
                }
            }
     
            // Supprime le contenu de toute la feuille
            public void Clear()
            {
                LateBindings.Invoke(LateBindings.Get(m_Worksheet, "Cells"), "Clear");
            }
     
            // Enregistre le fichier
            public void Save()
            {
                if (File.Exists(m_filename))
                    LateBindings.Invoke(m_Workbook, "Save");
                else
                {
                    int fileFormat =
                        string.Compare("11.0", this.Version) < 0 &&
                        m_filename.EndsWith(".xlsx", StringComparison.CurrentCultureIgnoreCase) ?
                        51 : -4143;
                    object[] param =
                        new object[8] { m_filename, fileFormat, string.Empty, string.Empty, false, false, 1, 1 };
                    LateBindings.Invoke(m_Workbook, "SaveAs", param);
                }
            }
     
            // Ouvre le processus Excel et le fichier donné (surchargé)
            public void Open(string filename)
            {
                Open(filename, null);
            }
     
            public void Open(string filename, string worksheetName)
            {
                m_Application = LateBindings.GetOrCreateInstance("Excel.Application");
     
                LateBindings.Set(m_Application, "DisplayAlerts", false);
     
                object workbooks = LateBindings.Get(m_Application, "Workbooks");
     
                m_filename = filename;
                if (File.Exists(filename))
                    m_Workbook = LateBindings.Invoke(workbooks, "Open", filename);
                else
                    m_Workbook = LateBindings.Invoke(workbooks, "Add", _mis);
     
                if (string.IsNullOrEmpty(worksheetName))
                    m_Worksheet = LateBindings.Get(m_Workbook, "Activesheet");
                else
                    m_Worksheet = GetWorksheet(worksheetName);
     
                SetWorksheetAttributes();
            }
     
            // Change de ligne
            public void NewLine()
            {
                if (m_StreamEnded)
                    throw new EndOfStreamException();
                if (m_RowIndex < m_RowCount)
                {
                    m_RowIndex++;
                    m_ColumnIndex = 1;
                }
                else
                    m_StreamEnded = true;
     
            }
     
            // Ecrit la valeur donnée dans la cellule courante et avance d'une cellule 
            // ou change de ligne s'il arrive à la fin d'une ligne.
            public void Write(object value)
            {
                if (m_StreamEnded)
                    throw new EndOfStreamException();
                object cells = LateBindings.Get(m_Worksheet, "Cells");
                object range = LateBindings.Get(cells, "Item", new object[2] { m_RowIndex, m_ColumnIndex });
                if (value is String)
                    LateBindings.Set(range, "NumberFormat", "@");
                LateBindings.Set(range, "Value2", value);
                if (m_ColumnIndex == m_ColumnCount)
                {
                    if (m_RowIndex < m_RowCount)
                    {
                        m_RowIndex++;
                        m_ColumnIndex = 1;
                    }
                    else
                        m_StreamEnded = true;
                }
                else
                    m_ColumnIndex++;
            }
     
            // Ecrit un ensemble de valeurs donné sous forme de tableau dans des cellules,
            // puis change de ligne à la fin.
            public void WriteLine(object[] values)
            {
                if (m_StreamEnded)
                    throw new EndOfStreamException();
                foreach (object val in values)
                {
                    if (m_ColumnIndex <= m_ColumnCount)
                    {
                        object range = LateBindings.Get(m_Worksheet, "Cells");
                        object cell = LateBindings.Get(range, "Item", new object[2] { m_RowIndex, m_ColumnIndex });
                        if (val is String)
                            LateBindings.Set(cell, "NumberFormat", "@");
                        LateBindings.Set(cell, "Value2", val);
                        if (m_ColumnIndex < m_ColumnCount)
                            m_ColumnIndex++;
                    }
                }
                if (m_RowIndex < m_RowCount)
                {
                    m_RowIndex++;
                    m_ColumnIndex = 1;
                }
            }
     
            // Colle le contenu du presse papier dans la feuille courante
            public void PasteFromClipboard()
            {
                object cells = LateBindings.Get(m_Worksheet, "Cells", new object[2] { 1, 1 });
                LateBindings.Invoke(m_Worksheet, "Paste", new object[2] { cells, false });
            }
     
            // Met à jour les nombres de lignes et de colonnes et la position du lecteur.
            private void SetWorksheetAttributes()
            {
                m_RowIndex = 1;
                m_ColumnIndex = 1;
                object rows = LateBindings.Get(m_Worksheet, "Rows");
                m_RowCount = (int)LateBindings.Get(rows, "Count");
                object cols = LateBindings.Get(m_Worksheet, "Columns");
                m_ColumnCount = (int)LateBindings.Get(cols, "Count");
            }
     
            // Retourne l'instance de la feuille donnée en paramètre, l'ajoute si elle n'existe pas.
            private object GetWorksheet(string worksheetName)
            {
                object worksheets = LateBindings.Get(m_Workbook, "Worksheets");
                try
                {
                    return LateBindings.Get(worksheets, "Item", worksheetName);
                }
                catch
                {
                    object ws = LateBindings.Invoke(worksheets, "Add", _mis);
                    LateBindings.Set(ws, "Name", worksheetName);
                    return ws;
                }
            }
        }
    }
    Cordialement
    Fichiers attachés Fichiers attachés

  2. #2
    Expert éminent sénior
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Février 2005
    Messages
    5 074
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Val de Marne (Île de France)

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

    Informations forums :
    Inscription : Février 2005
    Messages : 5 074
    Points : 12 120
    Points
    12 120
    Par défaut
    >je suis débutant en terme de programmation sur visual basic.

    Je crois qu'on l'a un peu deviné :
    - vous postez dans un forum VC++ .NET et non dans un forum VB.NET
    - le code, c'est du C# et pas du VB.NET

    Code bien écris, il suffit de changé la ligne 66 de la classe commande

    par
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    xlw.Open(filename,"feuil2");

  3. #3
    Invité
    Invité(e)
    Par défaut
    Merci,
    Je vais essayé de compiler tout ça

  4. #4
    Invité
    Invité(e)
    Par défaut
    Bonjour,
    J'ai encore une question:
    Avec la class "ExcelWrite" est-t-il possible d'intégrer des formules dans ma class "commands" après l'extraction d’attribut vers excel?
    Par exemple:
    - dans la cellule C31 -> =SOMME(C2:C30)
    - dans la cellule C32 -> =C2*TAN(ACOS(D2))+C3*TAN(ACOS(D3))
    - dans la cellule C33 -> =RACINE(C31^2+C32^2)

    Merci d'avance

  5. #5
    Expert éminent sénior
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Février 2005
    Messages
    5 074
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Val de Marne (Île de France)

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

    Informations forums :
    Inscription : Février 2005
    Messages : 5 074
    Points : 12 120
    Points
    12 120
    Par défaut
    http://msdn.microsoft.com/en-us/libr...e.formula.aspx

    Aux lignes 153 et 182
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    LateBindings.Set(range, "Value2", value);
    Si c'est une formule, il faut remplacer "Value2" par "Formula".
    Il faut faire un petit refactoring de la classe pour gérer ces 2 cas de figure.

Discussions similaires

  1. PCVUE:Extraction de donnée vers Excel
    Par ren973 dans le forum Automation
    Réponses: 7
    Dernier message: 19/08/2016, 11h08
  2. Extraction des données vers Excel
    Par developpeur_débutant dans le forum SQL
    Réponses: 5
    Dernier message: 01/06/2011, 11h44
  3. autocad vers excel
    Par autocadNUL dans le forum Général VBA
    Réponses: 7
    Dernier message: 12/06/2009, 07h40
  4. Réponses: 2
    Dernier message: 24/06/2008, 15h55
  5. Réponses: 1
    Dernier message: 03/08/2006, 12h34

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