- Please note that the above code assumes that you have already manipulated your data and stored it in the manipulatedData variable.
How can I export a table to the active Excel sheet?
5 views (last 30 days)
Show older comments
I have a bit of code that opens the active Excel spreadsheet.
%% Import data from Excel
% find open Design Brief (if multiple, chooses 'current')
DB = actxGetRunningServer('Excel.Application');
% choose Lab Report sheet
DBsheet = DB.ActiveWorkbook.Sheets;
DBsheet = DBsheet.get('Item',15);
DBsheet.Activate;
From here I run a bunch of code that manipulates the data as I need, but I am struggling with how to then write that data back into the active sheet. The sheet name is never the same, so I am trying to avoid specifying sheet names. I have tried using writetable, but have found no success.
0 Comments
Answers (1)
Mrutyunjaya Hiremath
on 24 Jul 2023
To write data back to the active sheet in Excel without specifying the sheet name, you can use the "actxserver" interface to interact with Excel directly. Here's an example of how you can do it:
% Assuming you have already imported data and performed your manipulations
% Get the active Excel application
ExcelApp = actxGetRunningServer('Excel.Application');
% Get the active workbook and active sheet
ActiveWorkbook = ExcelApp.ActiveWorkbook;
ActiveSheet = ExcelApp.ActiveSheet;
% Convert your manipulated data (e.g., a MATLAB matrix or cell array) to a table
% Assuming your data is stored in a variable called 'manipulatedData'
dataTable = table(manipulatedData);
% Get the size of the data table
[numRows, numCols] = size(dataTable);
% Get the range of cells to write to (assuming you want to start at cell A1)
range = ActiveSheet.Range(['A1:', ExcelApp.ActiveCell.Offset(numRows-1, numCols-1).Address]);
% Write the data to the active sheet
range.Value = dataTable;
% Save and close the workbook (optional, if you want to save the changes)
ActiveWorkbook.Save;
ActiveWorkbook.Close;
% Quit Excel application (optional, if you want to close Excel)
ExcelApp.Quit;
See Also
Categories
Find more on Spreadsheets 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!