I wrote two while loops to compute some data groups and to export each in XLS format to a file . I want to export each file with a generated name like FtPr0 or Ftr0P. Let us suppose my value for P is 50 and r0 = 10, then I want to export the file Ft5010.XLS or Ft1050.XLS. I tried string, string-join and many other similar operations, but I was unable to export my data correctly.

How can I fixe my code to perform the export correctly?

k1 = 1;
n2 = 5;
While[k1 <= n2, 
  r0 = 10*k1;
  j = 1;
  n1 = 5;
  While[j < n1, 
    P = 50*j;
    q[z_] := r0 + P z + P*15*z^3;
    Ft = List[];
    For[i = 0, i <= 21, i++, 
      z = N[1*10^-6 + i*5*10^-8];
      F = q[z];
      AppendTo[Ft, {z, F}]];
    (*Export["  Ft.xls", Ft,"XLS"];SystemOpen["  Ft.xls"]*)
    Export["Ft" <> ToString[P] <> "file.xls", Ft, "XLS"];
    j = j + 1]; 
    n2 = n2 + 1]
  • $\begingroup$ I made two change and it worked fine for me. First, I changed the last line to k1=k1+1 to stop the loop. I suppose n2 = n2-1 would also do it. Then I changed the export to Export["Ft" <> ToString[P] <> ToString[r0] <> ".xls", Ft, "XLS"]; That gave me 20 files. $\endgroup$
    – LouisB
    Jul 15, 2017 at 7:13

1 Answer 1


The Table[] command lets us avoid While and For loops. Here is a simpler way to export your data to one XLS file with multiple worksheets. First, we create a list of worksheet names that contain the values of P and r0

 wkshts = Flatten[
  Table["P " <> ToString[50 j] <> ";r0 " <> ToString[10 k1],
   {j, 4}, {k1, 5}], 1];

The above Table command along with Flatten gives us 20 worksheet names for our 4 values of P and 5 values of r0. Next, we generate our data. We need 20 sets of data. Each set has 21 rows and 2 columns. We can do it with one Table along with Flatten

data = Flatten[Table[
    N[{z, 10 k1 + P z + P*15*z^3} /. z -> ((5 i/100) + 1)/10^6 /. 
      P -> 50 j, 10],
    {j, 4}, {k1, 5}, {i, 21}], 1];

We could check that the dimensions are correct with Dimensions[data]. Now we export the data with this command

Export["Ft.xls", Sequence[Thread[wkshts -> data]]]

The result is one XLS file with 20 worksheets. Make sure the data is correct before using it.

This same approach could be used to generate 20 files names and write the 20 sets to them. Using Table can be much cleaner than using While and For.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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