How to search an Excel file for a certain column, then save that entire column?
7 views (last 30 days)
Show older comments
I am working on a project where columns could be out of order, so I cannot depend on saving data from these columns as they will change. The first row of each column is the name of the data that the column contains. I want to search for the name of the column then save the data from the column.
1 Comment
dpb
on 2 Feb 2018
Simplest is just read the sheet and do the lookup in memory. If the data are structured regularly readtable would be good choice as then you've got the facilities of table for selecting data.
Accepted Answer
Bob Thompson
on 2 Feb 2018
The table option may work, I personally don't have much experience reading tables. I tend to read excel files using the more common xlsread() command. For finding a specific column based on column title I have used.
[numbers,text,alldata] = xlsread(excelfile);
[headerRow,headerCol] = find(cellfun(@(x)~isempty(strfind(x,'header')),alldata));
By creating the xlsread array results you allow xlsread to input all of the data, instead of just the number results, this allows it to maintain any cells with text.
The array of the second command allows you to find the specific row and column for the matching string, 'header'. The find command is what actually brings up the row and column, while the cellfun command allows all cells within the specified array (datain) to be checked for the condition. If I remember correctly, strfind only works for an array of strings, so the isempty check and cellfun command are necessary to make this work with the mixed data in the datain array.
5 Comments
Bob Thompson
on 2 Feb 2018
"That's what the tilde is for... [~,~,alldata] = xlsread(excelfile);
But if the data in the spreadsheet are regular, readtable takes care of it all for you much more easily by returning the actual variable type and the column heading as the table variable name.
I strongly recommend you explore its capabilities in lieu of the above workaround -- until it that was the only choice but for most(*) things there's now a better way. "
Tips like this are why I keep coming back to these forums. Thanks.
More Answers (0)
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!