using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Threading;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using ExcelStreamLateBinding;
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.Format("{0}{1}.xls",
AcAp.GetSystemVariable("DWGPREFIX"),
Path.GetFileNameWithoutExtension((string)AcAp.GetSystemVariable("DWGNAME")));
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("NAME",
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;
}
}
}
using (ExcelWriter xlw
= new ExcelWriter
(filename
)) {
if (File.Exists(filename))
xlw.Clear();
xlw.WriteRange(table);
xlw.Worksheet.Get("Columns").Invoke("AutoFit");
object range = xlw.Worksheet.Get("Range",
xlw.Worksheet.Get("Cells", 1, 1),
xlw.Worksheet.Get("Cells", 1, table.Columns.Count));
range.Get("Font").Set("Bold", true);
xlw.Save();
if (System.Windows.Forms.MessageBox.Show(
_dispMsg, _expMsg, System.Windows.Forms.MessageBoxButtons.YesNo) ==
System.Windows.Forms.DialogResult.Yes)
{
xlw.ExcelApp.Set("DisplayAlerts", true);
xlw.ExcelApp.Set("Visible", true);
xlw.ExcelApp.Set("UserControl", true);
}
}
}
[CommandMethod("IATT")]
public void ImportAttributes()
{
string path = string.Format("{0}{1}.xls",
AcAp.GetSystemVariable("DWGPREFIX"),
Path.GetFileNameWithoutExtension((string)AcAp.GetSystemVariable("DWGNAME")));
OpenFileDialog dlg
= new OpenFileDialog
(_impMsg, path,
"xls;xlsx",
"",
0); if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
string filename = dlg.Filename;
System.Data.DataTable table;
using (ExcelReader xlr
= new ExcelReader
(filename
)) {
table = xlr.RangeToDataTable(1, 1);
}
if (table == null)
return;
using (Transaction tr = _db.TransactionManager.StartTransaction())
{
foreach (DataRow row in table.Rows)
{
try
{
ObjectId brId
= _db
.GetObjectId(false,
new Handle
(Convert
.ToInt64(row
[0].ToString(),
16)),
0); BlockReference br = tr.GetObject(brId, OpenMode.ForRead, true) as BlockReference;
if (br != null)
{
foreach (ObjectId id in br.AttributeCollection)
{
AttributeReference att = (AttributeReference)tr.GetObject(id, OpenMode.ForWrite);
if (table.Columns.Contains(att.Tag))
{
att.TextString = row[att.Tag].ToString();
}
}
}
}
catch { }
}
tr.Commit();
}
}
private Dictionary<string, string> GetAttributes(BlockReference br, Transaction tr)
{
Dictionary
<string,
string> result
= new Dictionary
<string,
string>(); foreach (ObjectId id in br.AttributeCollection)
{
AttributeReference att = (AttributeReference)tr.GetObject(id, OpenMode.ForRead);
result.Add(att.Tag.ToUpper(), att.TextString);
}
return result;
}
}
}