MATLAB Answers

How to write new data to the existing excel file?

13 ビュー (過去 30 日間)
Alex Zai
Alex Zai 2021 年 8 月 28 日
コメント済み: Simon Chan 2021 年 8 月 29 日
Respected All,
Hello everyone! I wanna add new data to the existing excel file from the last row of it. How can I do that please? I have tried and the error appeared "The number of table variables in an assignment must match.". And I opened that "Results.xlsx" file which is too small grid cells (attached photo).
Please someone suggest and help me. Thanks all.
Here example code:
Dtime = datetime('now','TimeZone','local','Format','d-MMM-y HH:mm:ss');
Name = {'Alex'};
DateAndTime = Dtime;
ConfidenceScore = 95;
if isfile('Results.xlsx')
T1 = readtable('Results.xlsx');
[rd, cd] = size(T1);
T = table(Name, DateAndTime, ConfidenceScore);
T1(rd+1, 1:cd-1) = T;
writetable(T1,'Results.xlsx');
else
T = table(Name, DateAndTime, ConfidenceScore);
writetable(T,'Results.xlsx');
end

回答 (1 件)

Simon Chan
Simon Chan 2021 年 8 月 28 日
You may replace the entire loop by using 'Append' as follows:
writetable(T,'Results.xlsx','UseExcel', true, 'WriteMode','Append')
  4 件のコメント
Simon Chan
Simon Chan 2021 年 8 月 29 日
If you still want to use the if-else-end, there is no need to use 'Append' for writetable.
The issue of having an error is simply due to the datetime format read back from the excel file which is not the same as the datetime format of the variable Dtime.
So you may try to convert the datetime format once again to make sure they are consistenct before writing to excel. (Added one line after readtable as shown below)
Dtime = datetime('now','TimeZone','local','Format','d-MMM-y HH:mm:ss Z');
Name = {'Alex'};
DateAndTime = Dtime;
ConfidenceScore = 80;
if isfile('Results.xlsx')
T1 = readtable('Results.xlsx');
T1.DateAndTime = datetime(T1.DateAndTime,'TimeZone','local','Format','d-MMM-y HH:mm:ss Z');
Tnew = table(Name, DateAndTime, ConfidenceScore);
T = [T1; Tnew];
writetable(T, 'Results.xlsx');
else
T = table(Name, DateAndTime, ConfidenceScore);
writetable(T,'Results.xlsx');
end

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by