I am programatically building an Excel spreadsheet in C# (joy!) and I am seeing bizarre behaviour in the Range.Top property.
I am building a network diagram (please don’t ask why I’m using Excel, but know that it wasn’t my decision and it cannot change) so many of the cells (nodes) are connected by lines (arcs) which are being drawn using Worksheet.Shapes.addLine(...). Unfortunately many of my arcs do not join up very well with my nodes.
Each time I add a node to the diagram (by filling a cell’s value with the node ID) I query its position so that I can calculate its center and use that as a line anchor point.
In one example I have seen when debugging I add two nodes, 1 at cell C3 and 2 at E3. For each cell the Range.Top property gives a different number!
Range cell = ws.Cells[3, 3]; // y (rows) before x (cols)
node.renderSmallerX = Convert.ToDouble(cell.Left); // e.g. 100
node.renderSmallerY = Convert.ToDouble(cell.Top); // e.g. 100
node.renderLargerX = node.renderSmallerX + Convert.ToDouble(cell.Width); // e.g. 130
node.renderLargerY = node.renderSmallerY + Convert.ToDouble(cell.Height); // e.g. 115
// ... (next loop)
Range cell = ws.Cells[3, 5];
node.renderSmallerX = Convert.ToDouble(cell.Left); // e.g. 100
node.renderSmallerY = Convert.ToDouble(cell.Top); // e.g. 114.25
node.renderLargerX = node.renderSmallerX + Convert.ToDouble(cell.Width); // e.g. 130
node.renderLargerY = node.renderSmallerY + Convert.ToDouble(cell.Height); // e.g. 129.25
I have read the manual and the measurement is to the top of the row, and in no way related to its content, so I see NO REASON why the property should change here.
I am so annoyed with this issue that I am now going to iterate over all required columns and rows first to create dictionaries of coordinates, rather than querying the position of cells as they are used, so that at least if they’re wrong they’re all wrong in the same way.
Can any Excel gurus explain this very odd outcome, or show me where I’m causing the problem? Many thanks.
EDIT: Should have mentioned – .NET v4, Microsoft.Office.Interop.Excel v11
I tried to simulate your problem in Excel 2003 by running the following code on a key press at various cells
I didn’t find
.Topto be different for cells in the same row, allthough I experimented with.VerticalAlignmentand boxes around the ranges with various line thicknesses.With various line thicknesses on at least one of the cells the
.Topchanges – but in sync for both cells. With different line thickness for both cells both.Topgo with the thicker line.One more difference between R1 and R2 in my
MsgBoxcan be seen for merged cells:R1.Heightreports total height whereasR2.Heightreports the height of the first cell only.Not an answer, but maybe an inspiration for you where to look next.