如何每次使用按钮将数据添加到 MATLAB 中的现有 XLSX 文件?

How to add data to existing XLSX file in MATLAB every time using a push button?

我有一个函数可以生成一些变量,比如分数、对、错、未回答。使用按钮调用此函数。问题是我如何每次将函数生成的这些值 add/append 写入 XLSX 文件?或者,如何创建 MAT 文件以便添加?可能的解决方案是什么?

追加到 xls 文件的挑战是知道它的最后一行,以避免用 xlswrite 命令覆盖数据。我建议您查看此文件交换提交 XLSAPPEND,因为它会为您解决这个问题。

听起来你有一个 GUI 运行 并且想要重复输出数据到一个 Excel 文件。可以加快文件输出速度的一个选项是保留 COM server open for output while your GUI is active, instead of repeatedly opening and closing one for every call to xlswrite or xlsappend。这是一个示例脚本来说明如何执行此操作:

function excel_output_example

  % Start COM server:
  excel = actxserver('Excel.Application');
  excelWorkbook = excel.Workbooks.Add(1);
  excelSheet = excel.ActiveSheet;
  fileName = 'example.xlsx';
  rowIndex = 1;  % Keeps track of the next row to output data to

  % Create GUI:
  hFigure = figure('Position', [100 100 120 70], ...
                   'DeleteFcn', @(~, ~) stop_excel(excelWorkbook, excel));
  uicontrol(hFigure, 'Style', 'pushbutton', ...
                     'Position', [20 20 80 30 ], ...
                     'String', 'Add to Excel', ...
                     'Callback', @output_to_excel);

  function output_to_excel(~, ~)  % Adds a random value to the next row in column A
    excelSheet.Range(sprintf('A%d', rowIndex)).Value = rand();
    rowIndex = rowIndex+1;
  end

  function stop_excel(workbookObj, comObj)  % Stops the COM server
    workbookObj.SaveAs(fileName);
    workbookObj.Close();
    comObj.Quit();
    comObj.delete();
  end

end

这将打开一个带有按钮的小型 GUI window。每次按下按钮时,都会在 Excel 文件的 A 列的下一个可用行中添加一个新的随机值。当 GUI window 关闭时,Excel 文件被保存并且 COM 服务器停止。例如,在按下按钮 5 次并关闭 GUI 后,您将在 Excel 文件中得到如下内容: