I hava a list just like

list = {{a1},

I want to save it to excel, but it will in different column like

enter image description here

Now I want they are all in the same column, maybe separate by comma or other mark symbol.

  • $\begingroup$ You could use Flatten[list] to get rid of all sub lists. $\endgroup$ – Sjoerd Smit Dec 18 '17 at 15:20
  • $\begingroup$ Could you give a screenshot of the desired output? That would make it much more clear what you want to achieve. $\endgroup$ – Sjoerd Smit Jan 17 '18 at 10:18

We can use the Row command to convert a list into comma separate values. However, we must convert the row into a string before we export. If we do this

  ToString[Row[#,","]]&  /@  list

then we get an Excel file with one column that contains only text data. Even if we set a1=3.14 in MMA, it will be text in Excel.

If our row contains only one value we do not need the Row command or the ToString command. So, we could do this

  If[Length[#] > 1,
    ToString[Row[#, ","]],
    First[#]] & /@ list

The second version will export rows that contain single numbers as numbers.

So far we have only considered a list of lists. What if we want to export this: list3 = { 3.14, {1, 4, 9} }; ? We would want the number 3.14 to appear in Excel, along the text "1, 4, 9". Here is how we could do it.

list3 = {3.14, {1, 4, 9}};
   Head[#] === List,
    If[Length[#] > 1,
     ToString[Row[#, ","]],
   True, #] & /@ list3

This code checks to see if the element is a list. If it is a list, and its length is greater than 1, we need to convert it to a row. Otherwise, we do not change the element.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.