Exporting Table contents
问题:
I would like to save the table contents to a file. How can I do this ?
解答:
AutoCAD command “TABLEEXPORT” can be used to save the contents of a table in the CSV format. One way to do this is to send this command using "SendStringToExecute".
You can also do the same thing without sending a command by traversing through the table contents as shown in the following code snippet:
public void commandMethodTest()
{
Document activeDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
Database db = activeDoc.Database;
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
PromptEntityOptions peo = new PromptEntityOptions("\nSelect a table : ");
peo.SetRejectMessage("\nMust be a table...");
peo.AddAllowedClass(typeof(Table), true);
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK)
return;
ObjectId oid = per.ObjectId;
String fileName = String.Empty;
SaveFileDialog sfd = new SaveFileDialog("Save As CSV", "Test", "csv", "Export Table As CSV", SaveFileDialog.SaveFileDialogFlags.AllowAnyExtension);
if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
{
return;
}
fileName = sfd.Filename;
StreamWriter sw = new StreamWriter(fileName);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
Table table = (Table)tr.GetObject(oid, OpenMode.ForRead);
int Rows = table.Rows.Count;
int Cols = table.Columns.Count;
for (int row = 0; row < Rows; row++)
{
String sRow = String.Empty;
for (int col = 0; col < Cols; col++)
{
if(sRow == String.Empty)
sRow = String.Format("{0}", table.Cells.GetTextString(FormatOption.FormatOptionNone));
else
sRow = String.Format("{0}, {1}", sRow, table.Cells.GetTextString(FormatOption.FormatOptionNone));
}
sw.WriteLine(sRow);
}
tr.Commit();
}
ed.WriteMessage("\nTable contents exported to " + fileName + " in CSV format.");
sw.Close();
}
页:
[1]