using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using System.Collections.Generic;
using System.Data.OleDb;
namespace CAPP3
{
public class CommandClass
{
[CommandMethod("VJUH")]
public void RunCommand()
{
Document adoc = Application.DocumentManager.MdiActiveDocument;
if (adoc == null)
return;
Editor ed = adoc.Editor;
Database db = adoc.Database;
Dictionary<string, string> tabTrans = new Dictionary<string, string>();
string excl_connection_string = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\Tst.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=YES""";
string sql = "SELECT * FROM [Sheet1$]";
OleDbConnection con = new OleDbConnection(excl_connection_string);
OleDbCommand cmd = new OleDbCommand(sql, con);
try
{
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
tabTrans.Add(reader.GetString(0), reader.GetString(1));
}
reader.Close();
}
catch (System.Exception ex)
{
ed.WriteMessage(ex.Message);
}
finally
{
con.Dispose();
}
using (Transaction tr = db.TransactionManager.StartTransaction())
{
// Take BTR from BT
BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
foreach (ObjectId btrId in bt)
{
// Take Id from BTR
BlockTableRecord btr = tr.GetObject(btrId, OpenMode.ForRead) as BlockTableRecord;
foreach (ObjectId Id in btr)
{
// Find all DBText
if (Id.ObjectClass == RXObject.GetClass(typeof(DBText)))
{
DBText text = tr.GetObject(Id, OpenMode.ForRead) as DBText;
//Find match and replace
string engText = null;
if (tabTrans.TryGetValue(text.TextString, out engText))
{
text = tr.GetObject(Id, OpenMode.ForWrite) as DBText;
text.TextString = engText;
}
}
// Find all MText
else if (Id.ObjectClass == RXObject.GetClass(typeof(MText)))
{
MText mtxt = tr.GetObject(Id, OpenMode.ForRead) as MText;
//Find match and replace
string engText = null;
if (tabTrans.TryGetValue(mtxt.Contents, out engText))
{
mtxt = tr.GetObject(Id, OpenMode.ForWrite) as MText;
mtxt.Contents = engText;
}
}
else if (Id.ObjectClass == RXObject.GetClass(typeof(BlockReference)))
{
BlockReference blkRef = tr.GetObject(Id, OpenMode.ForRead) as BlockReference;
AttributeCollection attRefCol = blkRef.AttributeCollection;
if (attRefCol != null)
{
foreach (ObjectId attRefId in attRefCol)
{
AttributeReference attRef = tr.GetObject(attRefId, OpenMode.ForRead) as AttributeReference;
{
string engText = null;
if (tabTrans.TryGetValue(attRef.TextString, out engText))
{
attRef = tr.GetObject(attRefId, OpenMode.ForWrite) as AttributeReference;
attRef.TextString = engText;
}
}
}
}
}
}
}
tr.Commit();
}
ed.Regen();
}
}
}