In the last post we saw some code to update an AutoCAD table linked to an Excel spreadsheet. In this post we go the other way, updating an Excel spreadsheet from a linked AutoCAD table.
Here's the C# code:
public class Commands
static public void UpdateSpreadsheetFromTable()
Document doc =
Database db = doc.Database;
Editor ed = doc.Editor;
PromptEntityOptions opt =
"\nSelect table with spreadsheet to update: "
"\nEntity is not a table."
PromptEntityResult per =
if (per.Status != PromptStatus.OK)
Transaction tr =
DBObject obj =
Table tb = (Table)obj;
// It should always be a table
// but we'll check, just in case
if (tb != null)
// The table must be open for write
// Update the data link from the table
// And the spreadsheet from the data link
ObjectId dlId = tb.GetDataLink(0, 0);
DataLink dl =
"\nUpdated the spreadsheet from the table."
catch (Exception ex)
Tables with linked spreadsheets are locked by default and display this glyph when you hover over them: . Before you run the code you will need to unlock the table by right-clicking the cell(s) you wish to edit:
One point to note is that the code will work even if the spreadsheet is open in Excel, but the contents will not be updated automatically - you have to close and reopen the file to see the results. And you will probably see this dialog come up twice:
For the best (most logical) results, the T2S command should really be run when the spreadsheet is not open in Excel. I expect it's possible to determine whether a spreadsheet is open in Excel from using standard file access functions in .NET (requesting exclusive access, to see whether it's possible to get it), but that's being left as an exercise for the reader (or for another day, at least :-).
For your convenience, here's a source file containing the code from the last three posts (command implementations for TFS, S2T and T2S).