Reputation: 799
I need to open an existing excel workbook from within Matlab using ActiveX. xlsread is unfeasible because too slow. After getting help from this forum (thanks!) I know that to create a new excel workbook from within matlab and fill it with output you do this:
%# Create and NAME the output file name
wbk=1;fName = fullfile(pwd, 'ALLSDtemp2');
%# create Excel COM Server
Excel = actxserver('Excel.Application');
Excel.Visible = true;
%# delete existing file
if exist(fName, 'file'), delete(fName); end
%# create new XLS file
wb = Excel.Workbooks.Add();
wsheet=1;
(...calculations...)
% Write output to excel file
Mat=[calculation_output];
% Select work book
wb.Sheets.Item(wsheet).Activate();
% Get Worksheets object
ws = wb.Sheets;
%# insert matrix in sheet
Excel.Range(cellRange).Select();
Excel.Selection.Value = num2cell(Mat);
But I can't figure out how to do this with an excel workbook that already exists. And my efforts to do so caused a "serious error" in my computer the other day. So I could really use some guidance.
Thanks
Upvotes: 2
Views: 5064
Reputation: 24147
I'm not sure from your question whether you wish to just modify an existing Excel file, or to modify an Excel file that is currently open in Excel.
If it's the first, then you can open it like this:
xl = actxserver('Excel.Application');
xl.Visible = true;
wb = xl.Workbooks.Open('path_to_my_excel_file');
and then continue with whatever modifications you want, as you're already doing.
If you want to access an Excel file that is currently open in Excel, use actxGetRunningServer
instead of actxserver
. You will connect to the running copy of Excel and be able to find whatever workbooks are open.
By the way, you don't need to select a range to change its value. You can just use ws.Range(cellRange).Value = myValue
. Might save you a few lines of code here and there.
Upvotes: 0
Reputation: 19880
XLSREAD is actually accessing the file through ActiveX, the same way you want to go. I don't see any reason to write you own (and hopefully clear of bugs) procedure.
If XLSREAD is too slow, you can use PROFILER to find performance bottlenecks in the function.
You can actually see what XLSREAD is doing if you type edit xlsread
. The m-file with the function will be opened in the MATLAB editor. You can learn the code and actually run it line by line with great MATLAB debugging tools.
Upvotes: 1