How to read .txt file and convert in to .xls

1 view (last 30 days)
Hi! I am beginner in using Matlab but I must have to learn it as I am doing a project on Matlab. I want to know how can I read .txt file and then how can I convert that file's particular parameters in to table or spread sheet like .xls format. For example I have a Test.txt file in which this data is written
Name: Hamad
Marks: 10.05
Average: 11.55
Attendance: 80%
Name: Johan
Marks: 10.55
Average: 10.50
Attendance: 75%
Name: Hamad
Marks: 11.50
Average: 10.25
Attendance: 70%
Name: Johan
Marks: 10.50
Average: 11.50
Attendance: 90%
Now I want results like table in which all the parameters will be in each block but a little different from ordinary tables, like whenever it reads "hamad" place its data in front of it and whenever it reads "johan" place data in front of it
please consider the results below as blocks of table as I don't know how to show accurately here
Name Marks Average Atdc Name Marks Average Atdc
hamad 10.05 11.55 80% Johan 10.55 10.50 75%
hamad 11.50 11.50 70% Johan 10.50 11.50 90%
  2 Comments
hamad ahmad
hamad ahmad on 5 May 2011
I am trying to use fread but I am not familiar with these things.

Sign in to comment.

Answers (1)

Oleg Komarov
Oleg Komarov on 5 May 2011
Considering a textfile as:
Name: Hamad
Marks: 10.05
Average: 11.55
Attendance: 80%
Name: Johan
Marks: 10.55
Average: 10.50
Attendance: 75%
Name: Hamad
Marks: 11.50
Average: 10.25
Attendance: 70%
Name: Johan
Marks: 10.50
Average: 11.50
Attendance: 90%
Open file
fid = fopen('C:\Users\Oleg\Desktop\test.txt');
Set options to read vertical text
opt = {-inf,'endofline','','whitespace',' \b\t\r\n','collectoutput',1};
Format of each vertical block (name, marks, average, attendance)
fmt = '%*s%s%*s%f%*s%f%*s%f%%';
Import
data = textscan(fid,fmt,opt{:});
fid = fclose(fid);
Basic manipulation
data = [data{1} num2cell(data{2})];
Then use xlswrite, example:
xlswrite('where.xlsx',data)

Community Treasure Hunt

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

Start Hunting!