How to search an Excel file for a certain column, then save that entire column?
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
dpb
2018-2-2
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.
采纳的回答
Bob Thompson
2018-2-2
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 个评论
Bob Thompson
2018-2-2
"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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import from MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!