通过 Matlab GUI 提取 Excel 中的特定变量



我在 Matlab中创建了一个 GUI,经过一些计算后,它会在工作区中显示各种变量,例如质量、密度、高度、功率和速度

我的第一个问题是我有一个按钮,我想让我将上述数据保存在以下格式的 Excel 文件中:

  1. 质量、密度和高度均采用不同的板材
  2. 功率和速度在同一张纸上,彼此相邻

无论我尝试什么,它都没有用,这就是为什么我只粘贴 GUI 中的函数:

function pushbutton1_Callback(hObject, eventdata, handles)

我的第二个问题是我有一个按钮,我想让我将上述任何变量保存在 Excel 文件中,我尝试了以下方法:

function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
    [filename, pathname] = uiputfile('*.xls', 'Choose a file name'); 
    outname = fullfile(pathname, filename); 
    xlswrite(outname, M);

我希望每次运行 GUI 时都能够使用我要提取的变量的名称设置 M,例如密度。

有人可以帮助我解决上述问题吗?

提前!

在我看来,对于问题的第一部分来说,xlswrite不是一个好的选择,因为如果你想处理异步写入同一工作表上的两个不同的变量,它不会让你在现有文件的现有工作表上附加数据。您必须通过actxserver实例改用 Excel 互操作性(有关详细信息,请参阅此页面(。

以下是将所有内容保存到文件的方法:

[filename,pathname] = uiputfile('*.xls', 'Choose a File'); 
if (~filename)
    errordlg('Invalid file name specified.');
end
e = actxserver('Excel.Application');
e.DisplayAlerts = false;
e.Visible = false;
wb = e.Workbooks.Add();
shts = e.ActiveWorkbook.Sheets;
sht1 = shts.Item(1);
sht1.Activate();
sht1.Name = 'Density';
sht1.Range(['A1:A' num2str(numel(D))]).Value = D; % your Density variable
sht2 = shts.Item(2);
sht2.Activate();
sht2.Name = 'Height';
sht2.Range(['A1:A' num2str(numel(H))]).Value = H; % your Height variable
sht3 = shts.Item(3);
sht3.Activate();
sht3.Name = 'Mass';
sht3.Range(['A1:A' num2str(numel(M))]).Value = M; % your Mass variable
shts.Add([],shts.Item(shts.Count));
sht4 = shts.Item(4);
sht4.Activate();
sht4.Name = 'Other';
sht4.Range(['A1:A' num2str(numel(P))]).Value = P; % your Power variable
sht4.Range(['B1:B' num2str(numel(S))]).Value = S; % your Speed variable
wb.SaveAs(fullfile(pathname,filename));
wb.Close();
e.Quit();
delete(e);

现在。。。对于问题的第二部分,初始模式几乎相同,只是添加了 inputDLG 用于选择要保存的适当变量。在这种情况下,您可以使用xlswrite因为它是处理所有内容的一次性调用:

variable = cell2mat(inputdlg('Enter the variable name to be saved:','Choose a Variable'));
switch (variable)
    case 'Density'
        data = D;
    case 'Height'
        data = H;
    case 'Mass'
        data = M;
    case 'Power'
        data = P;
    case 'Speed'
        data = S;
    otherwise
        errordlg('Invalid variable name specified.');
        return;
end
[filename,pathname] = uiputfile('*.xls', 'Choose a File'); 
if (~filename)
    errordlg('Invalid file name specified.');
end
xlswrite(fullfile(pathname,filename),data,variable,'A1');

问题 1:只需使用指定的工作表进行多次调用即可pushbutton2_Callback xlswritexlswrite(filename, A, sheet) .显然,文件名保持不变,A是您想要在该工作表上的数据。

问题 2:您问的是什么有点不清楚,但是如果您只想将其中一个选定的数据点保存到文件中,则可以创建列表框样式的 uicontrol,该样式具有要保存的数据类型。然后,如果要将该类型的数据保存到特定的列/行/工作表中,只需查询其值属性(例如。 get(listbox_handle, 'Value') (,并使用它来指定工作表和 xlrange,这也是xlswrite函数中的一个选项。我强烈建议您查看该功能的文档。

最新更新