writetables data on excel

8 vues (au cours des 30 derniers jours)
Nick Pappas
Nick Pappas le 6 Avr 2020
Commenté : Stephen23 le 13 Nov 2024 à 11:24
Hi guys,
I have an array and i convert it to a table so i can put it on an excel file. My problem is that i want to play more with the excel.
My code is scanning 200 data and then save them to an excel. My problem is with the current code if the code reach in the next cut spot at 400 data it will replace the old ones. I don't want that. I want to add the new 200 data under the old ones in the excel.So overal i will have 200 old data + 200 new data under of the old data.
In excel it could be A1:A200 and the new data to A201:401
Does anyone have any ideas on how to do it ?
Thank you for your time!
-Nick
My code is:
if (intex == 200)
T = array2table(myvar);
filename= 'Untitled1.xlsx';
writetable(T,filename,'Sheet',1,'Range','A4');
intex =0;
end
  1 commentaire
Stephen23
Stephen23 le 13 Nov 2024 à 11:24
The simplest approach is to specify the WRITEMODE as APPEND (which adds the new data underneath any existing data):

Connectez-vous pour commenter.

Réponses (1)

Deepak
Deepak le 13 Nov 2024 à 11:04
We can append data to an Excel file by first checking if the file already exists and then reading the current data to determine the last occupied row. This can be done usingxlsread function of MATLAB, which helps identify where the existing data ends.
Once we know the last row, we can convert the new data into a table using array2table and use the writetable function to write the new data starting from the next available row.
By specifying the appropriate range in writetable, we can add the new data below the existing entries, effectively appending it without overwriting any previous data.
Here is the MATLAB code to achieve the same:
if (intex == 200)
% Convert array to table
T = array2table(myvar);
filename = 'Untitled1.xlsx';
% Check if the file exists
if isfile(filename)
% Read the existing data to find the last row
[~, ~, raw] = xlsread(filename, 1);
lastRow = size(raw, 1);
else
lastRow = 0;
end
% Define the starting row for new data
startRow = lastRow + 1;
% Write the table to the file, appending it below existing data
writetable(T, filename, 'Sheet', 1, 'Range', sprintf('A%d', startRow));
intex = 0;
end
Attached is the documentation of functions referenced:
I hope this assists in resolving the issue.

Community Treasure Hunt

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

Start Hunting!

Translated by