I have a class Department:
class Department{
string des;
string name;
string id;
List<Department> subDeps;
}
As the code shown,one department may have several sub-departmens.
Now,I have read the information from database,and I get the root Department object.
Then I want to generate a excel worksheet like this manner:

In fact,The root "Department" object is a tree structure .
When I try to write the items to the excel sheet,I have to decide the rows and cols for the item,but I can not make it.
And one can do me a favor?
Look at it this way:
I used the same syntax as you to name the nodes (left side) and the corresponding position “(row,column)” into the grid (right side). There are two top level departments here, 0 and 1.
You can label your nodes with “(x,y)” coordinates with a depth first visit for every tree/top level department. Whenever you descend from father to child, you have to increase the column number by 1.
Every time you visit a new sibling your row index must refer to a new, empty one (in the example, the sibling of 10 is 11 but you can’t put it in (3,1) because row 3 is already occupied by dept 101).
I would write the algorithm following these guidelines. Keep track of the current (x,y) with two variables that are passed down as parameters of a recursive depth-first visit, together with the current node/department to be visited. Make sure that the function edits as required the excel representation but returns the maximum row index used (so that you can use it to know which is the following row when visiting a new sibling — as in the previous example).
Every time you make a recursive call you have to call it with coords (x, y+1) because it’s a new column. In a similar manner, when you visit a new sibling you call it with (coords prev_call_retn+1, y) because it’s a new row (where coords_prev_call_retn is the value of the last recursive call on the previous sibling).
An helper function will call the recursive one on the root node and using as base coords (0,0), or whatever you like to start from.
In this C++ code, label() is the function you’re interested in.
The parameters row and col are supposed to be the correct coordinates of the department *d, so that we can visit the node immediately.
The loop recursively calls label() on each children (if any). Note that I use the variable row in order to keep track of the last used row + 1.
Lastly, we have to return the last used row by the function, but being careful to subtract one if the d->subDepts is not empty. This is because the for loop that adds 1 extra row in the last iteration.
Here is an example main:
And here the result:
I hope this helps.