Write filename as the name of input file with append

8 ビュー (過去 30 日間)
Adi Purwandana
Adi Purwandana 2023 年 10 月 11 日
編集済み: Dyuman Joshi 2023 年 10 月 11 日
Hello,
I have an excel file (let's say dataset.xlsx) which then I do a sequence of processes and then get a new table of matrix, namely A. Does anyone know to save this matrix in excel and give the file name as the excel file name (i.e. dataset) and give an append "_modified"; so that the created new excel file will be:
dataset_modified.xlsx ?
warm regards,
PS.
My existing code, I do it manually as follow:
readtable('dataset.xlsx');
% Then I do sequence of process which create table of matrix "A"
filename = 'dataset_modified.xlsx'; % I want this to be automatically as the previous file name (dataset.xlsx)
writetable(A,filename,'Sheet',1);

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 10 月 11 日
編集済み: Dyuman Joshi 2023 年 10 月 11 日
I assume you have to do this for multiple excel files, and all the files are stored in the same folder (and the folder only contains the files needed).
%Get all the files that match .xlsx extension
z = dir('*.xlsx');
n = numel(z);
for k=1:n
%Name of the file
str = z(k).name;
%Read the contents of the file
mat = readtable(str);
%
%% Code for getting A from mat
%
%Get the modified name
newstr = regexprep(str,'(\w*).xlsx','$1_modified.xlsx');
%Write the data to the file with modified name
writetable(A,newstr,'Sheet',1)
end
  2 件のコメント
Adi Purwandana
Adi Purwandana 2023 年 10 月 11 日
編集済み: Adi Purwandana 2023 年 10 月 11 日
Thank you @Dyuman Joshi. Perfect for many files (please add * at z = dir('*.xlsx')). And Here is my code for single file after adopting your code:
file = 'dataset.xlsx';
[~,name,~] = fileparts(file);
newstr = regexprep(file,'(\w*).xlsx','$1_modified.xlsx');
writetable(A,newstr,'Sheet',1);
Steven Lord
Steven Lord 2023 年 10 月 11 日
A slightly simpler approach using string operations.
file = 'dataset.xlsx';
[~,name, ext] = fileparts(file)
name = 'dataset'
ext = '.xlsx'
newname = name + "_modified" + ext
newname = "dataset_modified.xlsx"
If you need newname to be a char vector (if the function that you want to pass newname into doesn't accept string arrays; most if not all MathWorks functions that accept char vectors should also accept string arrays) just call char on it.
newnamec = char(newname)
newnamec = 'dataset_modified.xlsx'

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSpreadsheets についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by