Saving file with file name from user
7 ビュー (過去 30 日間)
古いコメントを表示
I have code for push button where user will click on save, then a folder browser opens where user selects the folder to save the file.
Now here my code:
filename=('output.xls');
foldername = uigetdir;
% ensure the folder name is valid
if ischar(foldername)
% update the file name to include the folder name
filename = fullfile(foldername,filename);
% open the file
fid = fopen(filename,'w');
if fid>0
% write the data to file
fprintf(fid, '%6s\t%6s\t\n', 'x', 'y');
fprintf(fid, '%6.4f\t%6.41f\t\n', result);
fclose(fid);
end
end
So here by default the output file name will be output.xls
I want to have the user capability to set the name of the file. So how to do that?
0 件のコメント
採用された回答
Image Analyst
2015 年 4 月 30 日
Let the user type it in with uiputfile(). Here is my snippet for that:
% Get the name of the file that the user wants to save.
% Note, if you're saving an image you can use imsave() instead of uiputfile().
startingFolder = userpath
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uiputfile(defaultFileName, 'Specify a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
9 件のコメント
Adi Purwandana
2023 年 2 月 28 日
I found the solution already... just type '*.xls' to replace '*.*' thank you.
Image Analyst
2023 年 2 月 28 日
@Adi Purwandana These days we use .xlsx rather than .xls to ensure you get the modern format of the workbook.
その他の回答 (1 件)
Stephen23
2015 年 4 月 30 日
編集済み: Stephen23
2015 年 4 月 30 日
3 件のコメント
Stephen23
2015 年 4 月 30 日
編集済み: Stephen23
2015 年 4 月 30 日
The path and file arguments around the wrong way in the fullfile call, it should be:
filename = fullfile(PathName,filename);
When you have a problem like this it helps to use the debugging tools, as mistakes like this are easy to find when you check the variables during line-by-line code evaluation.
Note also that you specify the file extension as .xls, but you have opened a textfile and are using fprintf to write text data. This does not make any sense, as .xls files are not text files, but binary files.
You need to decide if you want to work with textfiles or excel files, and then either:
- use a file extension that is suitable for textfiles and will not be mistaken for an .xls file.
- save an .xls file using xlswrite.
参考
カテゴリ
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!