Converting .xls and .xlsx to .csv

Hey guys,
I was wondering if there was a way I could ask a user if their file is .csv, and if not, I would sent it through a loop to have it converted to .csv. Is there any way I could do that?
Thanks!

 Réponse acceptée

Image Analyst
Image Analyst le 7 Déc 2014
Modifié(e) : Image Analyst le 7 Déc 2014

0 votes

Why not assume the extension is correct and process it if necessary?
[folder, baseFileName, extension] = fileparts(filename);
if strcmpi(extension, '.xlsx')
numbers = xlsread(filename);
csvFileName = strrep(filename, '.xlsx', '.csv');
csvFileName = strrep(csvFileName, '.xls', '.csv');
csvwrite(csvFileName, numbers);
end

5 commentaires

Ali
Ali le 4 Oct 2018
Modifié(e) : Ali le 4 Oct 2018
great! How about if we have number and text in our excel file?
Image Analyst
Image Analyst le 5 Oct 2018
You can make up a cell array and use xlswrite(). Or you can make a table and use writetable().
Ali
Ali le 5 Oct 2018
Thanks a lot. I used xlswrite() and It was the solution.
Vikas Saroha
Vikas Saroha le 22 Juil 2020
But it writes only numbers not including row and colomn headers. How these can be included in the .csv file?
Image Analyst
Image Analyst le 22 Juil 2020
You can use fprintf() to write it out exactly as you want.

Connectez-vous pour commenter.

Plus de réponses (2)

Harish TV
Harish TV le 17 Mar 2017

0 votes

clear; clear all; fileip='filename.csv'; g=char(fileip); g=g(1:end-4) fileop=horzcat(g,'.xlsx') g=fileip(1:end-4); [~,~,F]=xlsread(fileip); F=cellstr(F); %delete the header rows (4 rows) F([1:4],:)=[]; for a=1:size(F,1); b=F(a,1); c=char(b); D(a,:)=strsplit(c,','); end xlswrite(fileop,D); disp(['--------------Process complete---------------------']);
sapna kumar
sapna kumar le 11 Jan 2019

0 votes

file = dir('*.xlsx'); % make sure your are navigated to the right folder on matlab
s= size(file,1);
for i= 1:s
Data = xlsread(file(i).name);
filename=file(i).name;
filename= filename(1:end-5); % to remove extension from filename
csvwrite([filename '.csv'], Data);
end

Catégories

En savoir plus sur App Building dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by