问题
I have a cell array myFile 637x16. The first row of the cell array is made of strings, because they will be the columns' labels in the .xlsx/.csv file.
From the second row on, the cell array is made of some columns with strings, and some columns with numbers. I would like to export this cell array as a .xlsx or .csv file.
Here is an example of what I have:
'subject' 'PeakA' 'PeakL' 'number' 'epoch' 'code' 'type' 'latency' 'nitem' 'condition' 'ia' 'cover' 'variety' 'init_index' 'init_time' 'urevent'
5 3.50 82 13 1 201011 'pre' 2502 201 1 1 'y' 'h' 13 13.92 13
5 -1.27 112 55 2 61011 'pre' 8213 61 1 1 'y' 'h' 55 53.90 55
5 6.59 99 85 3 124011 'pre' 13924 124 1 1 'y' 'h' 85 82.45 85
5 12.65 105 127 4 178011 'pre' 19635 178 1 1 'y' 'h' 127 122.43 127
5 -0.35 105 157 5 89011 'pre' 25346 89 1 1 'y' 'h' 157 150.98 157
5 10.29 93 163 6 132011 'pre' 31057 132 1 1 'y' 'h' 163 156.69 163
5 4.61 65 193 7 166011 'pre' 36768 166 1 1 'y' 'h' 193 185.25 193
5 1.45 51 199 8 212011 'pre' 42479 212 1 1 'y' 'h' 199 190.96 199
I tried:
xlswrite('filename.xlsx', myFile);
but it gives me this error:
Warning: Could not start Excel server for export.
XLSWRITE will attempt to write file in CSV format.
> In xlswrite (line 174)
Error using xlswrite (line 187)
An error occurred on data export in CSV format.
Caused by:
Error using dlmwrite (line 112)
The input cell array cannot be converted to a matrix.
回答1:
If you have a sufficiently recent version of Matlab (R2013b or older), writetable
is your friend.
%# create a table
tbl = cell2table(yourCellArray(2:end,:),'variableNames',yourCellArray(1,:));
%# write to file
writetable(tbl,'filename.xlsx')
If you want to use xlswrite
, it may be worth converting all data to string first, or to write the variable names separately, before you write the rest - I believe Matlab checks data types on the first row, which can cause typecast errors.
来源:https://stackoverflow.com/questions/33869367/save-a-cell-array-in-matlab-as-xlsx-or-csv-file