# How to produce a table with column and row headers included?

n = Table[i^2 + j*3, {i, 3}, {j, 7}] // TableForm
Export["stuck.xls", n]

4  7  10  13  16  19  22
7  10 13  16  19  22  25
12 15 18  21  24  27  30


What I want is to have the cell columns and rows give me exactly what i and j were, like this:

    j   1   2   3   4   5   6   7
i
1       4   7   10  13  16  19  22
2       7   10  13  16  19  22  25
3       12  15  18  21  24  27  30


From this I can see that the result of i=3 and j=7 is 30.

Can anyone help with this task?

• this did not paste like I expected. The columns should have been 7 wide (as shown) but the rows should have been 3 deep. The place where you see a number 2 should have been the start of a new row and where the number 3 shows should have been the start of the third row . . . .sorry for the confussion – John Jan 9 '15 at 5:35
• I fixed your post for you. Welcome to the site. Please have a look at the faq, and you may also want to see the revised source code of your question that produced this formatting. – Oleksandr R. Jan 9 '15 at 5:40
• Hi Oleksandr,That was a speedy reply . . .thank you much – John Jan 9 '15 at 5:46
• sorry, hit return too soon . . .where exactly can i see the "revised code" you referenced . . .thx again – John Jan 9 '15 at 5:46
• Click on the "edited <> ago" text to see that: here. – Oleksandr R. Jan 9 '15 at 5:50

You can pad n with required column and row headers before exporting to Excel:

padF = With[{d = Dimensions[#], ap = ArrayPad[#, {{1, 0}, {1, 0}}, ""]},
Transpose@Prepend[Transpose[Join[{Prepend[Range@d[[2]], "j"]}, ap]],
Join[{"", "i"}, Range@d[[1]]]]] &;

n = Table[i^2 + j*3, {i, 3}, {j, 7}];
Export["stuck2.xlsx", nn]


You are looking for the TableHeadings option of TableForm.

table = Table[i^2 + j*3, {i, 1, 3, .5}, {j, 1, 7, .5}];
{rowVar, columnVar} = {"i", "j"};



If you want to show the row and column variable names then you have to pad the data with empty strings to make room for the extra labels.

TableForm[
ArrayPad[table, {{1, 0}, {1, 0}}, ""],
]


Note: Data should be left as data (Table or List); separate from presentation (TableForm). That way you can choose to display it as a TableForm, MatrixForm, or easily work with the data the later on. In particular

(* Bad practice *)
n = Table[i^2 + j*3, {i, 3}, {j, 7}] // TableForm;
(* Fail *)


Edit: There used to be an answer by @kguler which addresses exporting the headers to Excel by prepending the headers to the data. This uses the same method, perhaps in a more easily readable format.

formatTable[table_, {rowHeaders_, columnHeaders_}, {rowVar_, columnVar_}] :=
table //
ArrayPad[#, {{1, 0}, {1, 0}}, ""] & //

• TableHeadings->{Range[1,3,.1],Range[1,7,.1]} – Timothy Wofford Jan 9 '15 at 6:25