match 2 column values of 2 excel files , when values are matched then write a table in second excel file against 1st column value

1 view (last 30 days)
Hi, i have 2 excel files. I want to match one column value from first file and one column value from second file. values match one by one . when matched values , then a table values writes on second file.

Answers (1)

Sameer
Sameer on 18 Sep 2024
Hi Rabia
From my understanding, you want to match the "Person name" column from "firstfile.xlsx" with the "Person name" column from "secondfile.xlsx". When a match is found, you want to write the corresponding "Date" from the first file and the "Time" from the second file into a new table, which will then be written back into the second Excel file.
Here’s how you can achieve this:
% Read data from the first Excel file
firstFileData = readtable('firstfile.xlsx');
% Read data from the second Excel file
secondFileData = readtable('secondfile.xlsx');
% Initialize an empty array to store matched results
matchedResults = [];
% Iterate through each row in the first file
for i = 1:height(firstFileData)
% Get the current person name from the first file
personNameFirstFile = firstFileData.PersonName{i};
% Find matching rows in the second file
matchIdx = strcmp(secondFileData.PersonName, personNameFirstFile);
% If there is a match, store the matched data
if any(matchIdx)
% Get the corresponding date and time
dateValue = firstFileData.Date(i);
timeValue = secondFileData.Time(matchIdx);
% Append the matched results
matchedResults = [matchedResults; {personNameFirstFile, dateValue, timeValue}];
end
end
% Convert the matched results to a table
matchedTable = cell2table(matchedResults, 'VariableNames', {'PersonName', 'Date', 'Time'});
% Write the results back to the second Excel file
writetable(matchedTable, 'secondfile.xlsx', 'Sheet', 'MatchedResults');
disp('Matching completed and results written to secondfile.xlsx');
Hope this helps!

Products

Community Treasure Hunt

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

Start Hunting!