xlsread User defined file
1 次查看(过去 30 天)
显示 更早的评论
Hey,
I want to use the xlsread command to read in date from a file. I know the way to use the command is as
data = xlsread('data_file.xlsx','Sheet1');
I want to use it a slightly different way, where I would have a prompt command on the screen asking the user to input the file name and then the sheet name. And it is then these user defined file name and sheet name which are used in the xlsread command.
Is that possible?
0 个评论
回答(1 个)
Image Analyst
2013-9-20
Here's one way.
% Have user browse for a file, from a specified "starting folder."
% For convenience in browsing, set a starting folder from which to browse.
startingFolder = 'C:\Program Files\MATLAB';
if ~exist(startingFolder, 'dir')
% If that folder doesn't exist, just start in the current folder.
startingFolder = pwd;
end
% Get the name of the file that the user wants to use.
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uigetfile(defaultFileName, 'Select a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullExcelFileName = fullfile(folder, baseFileName)
% Ask user for a sheet name.
defaultValue = 'Sheet1';
titleBar = 'Enter a sheet name';
userPrompt = 'Enter the sheet name ';
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
sheetName = strtrim(char(caUserInput))
[num, txt, raw] = xlsread(fullExcelFileName, sheetName);
It's not as robust or user friendly as I nromally have it, though more so than others typically do. For example, it would be far nicer if you used ActiveX to determine what the sheet names are in the workbook and then ask the user to pick one of them via a listbox or the menu() functions. Another thing you need to do is to check for an error if the user types in a sheet name that does not exist and alert the user and take corrective action. In other words, as long as this code is, with three verification "if" sections, you should make it even more robust.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Environment and Settings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!