How to compare excel sheet data with user input?

2 次查看(过去 30 天)
This is the content of my Excel sheet
RollNo Name
  • 1 Abdul
  • 2 Barely
  • 3 Carol
  • 4 Pegi
Now I need to take user input for rollno in MATLAB and check it with the excel sheet, whether that rollno is matches or not. If matches then show warning Duplicate entry else enter that record in Excel sheet

回答(1 个)

Garv Agarwal
Garv Agarwal 2023-7-11
Hi Naomi,
From my understanding, you want to compare user input with data already present in an Excel file and input it in the sheet if it is a new entry.
You can do this by first reading the Excel sheet -
opts = spreadsheetImportOptions("NumVariables", 2);
% Specify sheet and range
opts.Sheet = "Sheet1";
% Specify column names and types
opts.VariableNames = ["RollNo", "Name"];
opts.VariableTypes = ["double", "string"];
filepath= "PATH TO YOUR SHEET";
% Import the data
data = readtable(filepath, opts, "UseExcel", false);
Then take user input using the input function and check to see if such an entry exists or not using the find function. If it is a new entry, then we input it into the sheet using writecell function -
roll = input('Enter Roll no.: ');
% If the input entry doesn't exist, then the find funtion will return an
% empty matrix
if isempty(find(data.RollNo==roll, 1))
name = input('Enter Name: ',"s");
info={roll,name};
writecell(info,filepath,'WriteMode','append');
else
disp("Duplicate Entry")
end
For more details, you can refer to the following documentations on reading and writing from excel sheets and the input function -

Community Treasure Hunt

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

Start Hunting!

Translated by