1
votes

I am stuck trying to export matlab uitable data to excel. I tried many things, and It has been impossible to solve this problem. After many days, I tried the code below using windows and it does work perfect, however, using the same for Macintosh is not longer working. The output is as follows:

"Error using dlmwrite (line 118) The input cell array cannot be converted to a matrix"

Searching for more information, I found an answer here ,(Using "xlswrite" MATLABs for cell arrays containing strings of different size) which doesn't work perfect. Finally I found this method which applies only for matlab using windows (http://www.mathworks.es/matlabcentral/answers/20819-export-uitable-s-data-to-a-spreadsheet-excel).

I hope you can help me with this problem.

Thanks in advance

Hector

function Save_File

hf = figure;

hExportButton = uicontrol('Parent',hf,'Units',...
'normalized','Position',[0 0.81 0.22 0.18],'Style','Pushbutton',....
'String',' Export Data!','FontSize',20,'Callback',@ExportButton_Callback);

dat = rand(5,5); 

t=uitable('Data',dat,'ColumnName',{'First','Second','Third','Fourth','Fifth'},...
'Position',[7 10 500 300]);

Data=get(t,'Data');
ColumnName=get(t,'ColumnName');
set(t,'ColumnWidth',{93.5})


function ExportButton_Callback(~,~)

NewData= num2cell(Data,ones(size(Data,1),1),ones(size(Data,2),1));
CombData=[ColumnName';NewData];
FileName = uiputfile('*.xls','Save as');
xlswrite(FileName,CombData);  
end

end
1
The issue is likely that you have an array that contains both strings and numbers, these can not be placed together into a single matrix, I would recommend simply writing your file line by line as a csv. A csv file can be opened by Excel - MZimmerman6
This doesn't even work in R2013b. Don't bother with xlswrite. Have you checked out the MathWorks FileExchange? There seem to be several options available that don't even require Excel. - horchler

1 Answers

2
votes

You should be able to convert the cell array into a number array with a cell2mat command and then use csvwrite or dlmwrite.

If the combo of numbers and strings is the issue, as stated in my comment above, you can use some simple looping to do this all for you. I posted some sample code below.

% Creating some temporary data for proof of concept
mat = randi([1,5],10,2);
header = {'Col1','Col2'};
cellVals = [header;num2cell(mat)];

% the real code that does the writing
fh = fopen('temp.csv','w'); % open a file with write privileges, will overwrite old versions
for ii = 1:size(cellVals,1)
    first = 1;
    for  jj = 1:size(cellVals,2)
        if first
            fwrite(fh,num2str(cellVals{ii,jj},'%f'));
            first = 0;
        else
            fwrite(fh,[',',num2str(cellVals{ii,jj},'%f')]);
        end
    end
    fwrite(fh,sprintf('\r\n')); % print line break
end
fclose(fh); % close file out when done writing