Writing data to multiple Excel ranges
Show older comments
I am using an Excel document as the basis for a test report. The 'Data' tab contains some named ranges for meta data (date, sample ID, batch, etc); these are single cells. The sheet also contains named ranges in which to record measured data. These ranges are variously columns (1D), or blocks (2D). I am trying to intentionally write to each of these ranges discretely, to maintain flexibility (so the code does not have to change if the Excel document changes). If I use a series of writecell/writematrix calls, MATLAB seems to sporadically get hung up on file permissions. It seems that the writecell/writematrix functions do not always properly release the file upon completion.
I am open to solutions with native MATLAB code, or using the Excel .NET interface. As ActiveX is depricated, I am trying to avoid it.
MATLAB 2024B, Excel 2016, on Windows 11 Enterprise.
% These are nested functions; fileOut is shared with the parent function.
function writeNumeric(sheet, range, data)
writematrix(data, fileOut,...
"FileType", "spreadsheet",...
"Sheet", sheet,...
"Range", range,...
"AutoFitWidth", false)
end
function writeString(sheet, range, s)
writecell(s, fileOut,...
"FileType", "spreadsheet",...
"Sheet", sheet,...
"Range", range,...
"AutoFitWidth", false)
end
Accepted Answer
More Answers (2)
Walter Roberson
on 5 Jan 2026
Moved: dpb
on 5 Jan 2026
0 votes
It is known that for efficiency, MATLAB might leave excel documents open between read* and write* calls. It is not at all clear when MATLAB releases the files.
"...solutions with native MATLAB code, or using the Excel .NET interface."
OK, I got curious enough to go looking -- I had previously mistakenly thought .NET was another layer but still using the Excel instance, but actually the .NET API interacts directly with the native file format. This makes it much more attractive, indeed, at the expense of learning another API documented in C# code rather than VBA.
But, I got the following to work; I didn't pursue the API in more depth; with the help of the MATLAB doc on using Excel with .NET and asking specific functionality of AI that generated example code for things not shown in the limited examples:
dotnetenv('framework'); % requires R2022b+
NET.addAssembly('microsoft.office.interop.excel');
app = Microsoft.Office.Interop.Excel.ApplicationClass;
fqn=string(fullfile(pwd,'Book1.xlsx')); % create fully-qualified filename
wbk=app.Workbooks.Open(fqn); % open the file, returns a WorkbookClass object
wantedsheet='Sheet1'; % set the wanted sheet to address
wkshts=wbk.Worksheets; % returns a sheets collect COM object
wksht=Item(wkshts,wantedsheet); % select the wanted sheet
wksht=Microsoft.Office.Interop.Excel.Worksheet(wksht); % this is key -- the COM object is not populated directly
% first let's read what is in the given named range...
rnge=Range(wksht,'RangeA') % create a named range object
data=rnge.Value2; % again, a COM object, not the actual data
data=cell(data,'ConvertTypes',{'all'}); % MUST convert to MATLAB type
data=cell2mat(data); % if all numeric
% if all data in the range are known to be numeric, above can be shortened as
%data=cell2mat(cell(rnge.Value2));
% now write some other data in its place...
data=rand(size(data)); % arbitrary block of values
rnge.Value2=data; % store it
wbk.Save % and save the workbook
wbk.Close(0) % and close
System.Runtime.InteropServices.Marshal.ReleaseComObject(rnge);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wksht);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wkshts);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wbk);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
After the .Open() I checked about whether it was really so via
>> !dir /b /a:h *Book1.xlsx
~$Book1.xlsx
>> wbk.Close
>> !dir /b /a:h *Book1.xlsx
File Not Found
>>
and the hidden backup file was there when open and not once close.
it's not as straightforward as is translating ActiveX VBA syntax to MATLAB-callable equivalent; the need to cast returned COM objects to specific types is different and it is not clear precisely when this is or is not needed nor the syntax to do so. I found the above only via the example/AI-generated code, not in the use documentation. You'll probably find asking an AI bot for "How do I ... with .NET in MATLAB?" a very frequent tool if doing anything but the most basic.
I also leanred that the Value2 property is recommended over using the Value property for speed and avoiding the Excel propensity to convert dates internally; it is a parallel property that contains the underlying data value and doesn't support the Time or Currency formatting types that Value does. That is, in fact, documented at the MS Learn site.
The <Ineract with Excel by .NET> doc page will provide some vital klews, but certainly won't be all you'll have to figure out.
Categories
Find more on Data Import from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
