Filter löschen
Filter löschen

How can I export a table to the active Excel sheet?

17 Ansichten (letzte 30 Tage)
Jesse Finnell
Jesse Finnell am 24 Jul. 2023
Kommentiert: Jesse Finnell am 24 Jul. 2023
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.

Antworten (1)

Mrutyunjaya Hiremath
Mrutyunjaya Hiremath am 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;
  • Please note that the above code assumes that you have already manipulated your data and stored it in the manipulatedData variable.
  1 Kommentar
Jesse Finnell
Jesse Finnell am 24 Jul. 2023
I have this line
range = DBsheet.Range(['L16:', DB.ActiveCell.Offset(rows-1, cols-1).Address]);
and I receive the error,
Index in position 1 exceeds array bounds. Index must not exceed 1.

Melden Sie sich an, um zu kommentieren.

Produkte


Version

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by