【问题标题】:Exporting uitable data to excel using matlab for macintosh使用 matlab for macintosh 将 uitable 数据导出到 excel
【发布时间】:2014-02-28 22:24:38
【问题描述】:

我被困在试图将 matlab uitable 数据导出到 excel 中。我尝试了很多东西,但一直无法解决这个问题。很多天后,我使用 windows 尝试了下面的代码,它确实可以完美运行,但是,在 Macintosh 上使用相同的代码不再有效。输出如下:

“使用 dlmwrite 时出错(第 118 行)输入元胞数组无法转换为矩阵”

搜索更多信息,我在这里找到了答案,(Using "xlswrite" MATLABs for cell arrays containing strings of different size) 并不完美。最后我发现这个方法只适用于使用 windows 的 matlab (http://www.mathworks.es/matlabcentral/answers/20819-export-uitable-s-data-to-a-spreadsheet-excel)。

希望你能帮我解决这个问题。

提前致谢

赫克托

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

【问题讨论】:

  • 问题可能是你有一个同时包含字符串和数字的数组,这些不能一起放在一个矩阵中,我建议你简单地将文件逐行写为 csv。 Excel可以打开一个csv文件
  • 这在 R2013b 中甚至不起作用。不要打扰xlswrite。您检查过 MathWorks FileExchange 吗?似乎有 several options available 甚至不需要 Excel。

标签: excel matlab user-interface matlab-uitable


【解决方案1】:

您应该能够使用cell2mat 命令将元胞数组转换为数字数组,然后使用csvwritedlmwrite

如果数字和字符串的组合是问题,如我在上面的评论中所述,您可以使用一些简单的循环来为您完成这一切。我在下面发布了一些示例代码。

% 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

【讨论】:

  • 不要使用num2str 没有第二个参数作为浮点输入。无论如何sprintf('%.17g',cellVals{ii,jj})) 会好很多。
  • 亲爱的@MZimmerman6,感谢您的帮助和建议。您的示例代码效果很好。非常感谢您的热心帮助!!!!
  • @horchler 不错。注意所有格式标志都可以看到here
  • 亲爱的@MZimmerman6,我将您的示例改编为我的代码,效果很好。但是,我有一个新问题,第一个单元格包含一个字符串而不是数字,当我运行代码时,第一个单元格显示 NaN 消息。在这种情况下我能做什么?提前谢谢!!!
  • 我不完全确定我了解您遇到的问题。您能否编辑您的问题以显示您的意思的示例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多