xlsread User defined file

1 次查看(过去 30 天)
Mazhar
Mazhar 2013-9-20
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?

回答(1 个)

Image Analyst
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.
  1 个评论
Mazhar
Mazhar 2013-9-20
Its definitely better than I have right now, where the user has to go in to the script and change it there manually.
Going to give this a go,
Thanks,

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by