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

假装没事ソ 提交于 2021-02-17 02:37:04

问题


I have a function which generates some variable, like score, right, wrong, unanswered. This function is called using a push button. The problem is how can I add/append these values generated by a function to an XLSX file every time? Or, how to create a MAT file so that it can be added? What may be a possible solution?


回答1:


The challenge involved in appending to a xls file is knowing its last row, to avoid overwriting data with the xlswrite command. I'd suggest taking a look at this file exchange submission XLSAPPEND, as it takes care of this for you.




回答2:


It sounds like you've got a GUI running and want to repeatedly output data to an Excel file. One option that may speed file output is to keep a COM server open for output while your GUI is active, instead of repeatedly opening and closing one for every call to xlswrite or xlsappend. Here's a sample script to illustrate how you could do this:

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

This will open a small GUI window with a push button. Every time the button is pressed, a new random value will be added the the next available row in column A of the Excel file. When the GUI window is closed the Excel file is saved and the COM server stopped. For example, after pushing the button 5 times and closing the GUI you will get something like this in your Excel file:



来源:https://stackoverflow.com/questions/29544792/how-to-add-data-to-existing-xlsx-file-in-matlab-every-time-using-a-push-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!