Reading Text files and Writing to Excel sheets

I am using MatlabR2011a on my Windows 7 machine. I have a folder of 635 text files. Each file contains multiple rows and 2 columns. I am trying to loop through the folder and read each file and write these values to excel. So far this is what I have:
close all; clc;
dirname = uigetdir;
Files = dir(fullfile(dirname,'*.txt'))
for k = 1:635
j =1
filename = fullfile(dirname,Files(k).name);
fid = fopen(filename);
x = fgetl(fid)
while ischar(x)
x = fgetl(fid)
a2 = strtrim(x);
a3 = textscan(a2,'%s');
a4 = a3{1}{1};
a5= a3{1}{2};
pos3 = strcat('A',num2str(j));
xlswrite('sample_output',{a4,a5},'Sheet1',pos3)
j = j+1;
end
fclose(fid);
end
It keeps giving me the following error after it finishes reading the first file.
Error using ==> strtrim Input should be a string or a cell array of strings.
A sample input file looks like this:
15076 4636259
15707 4636299
15714 1781552
15721 4204950
15730 2174919
16209 4636510
16413 4758572
16470 4445808
17519 311397
17667 2116489
17739 1729694
18024 3210756
18627 3714194
18695 4192858
19141 632766
19318 1923574
19438 1255216
19493 4635020
19771 4770250
How can I fix this? Would appreciate help with this!

Answers (1)

You're making it pretty hard on yourself, using the file I/O functions.
Try using the textread function to slurp everything in:
[col1, col2] = textread( filename, '%s%s' );
Then you can write the array out with one call to xlswrite.

7 Comments

Sorry, I had an error in that code. Need to specify two outputs. Have edited to correct it.
Beware, also, that dir() doesn't necessarily return the file names in order. Just because you asked for the first file, doesn't mean it's called '1.txt'. If you want to output your files in order, make sure you sort the filenames array first.
Thanks for the reply. This is what I have now:
dirname = uigetdir;
Files = dir(fullfile(dirname,'*.txt'))
for i=1:635
filename = fullfile(dirname,Files(k).name);
[col1, col2] = textread( filename, '%s%s' )
pos = strcat('A',num2str(i));
xlswrite('sample_output',{col1,col2},'Sheet1',pos)
end
I don't see anything being written to the excel file though...
Darn it! how do i put code in the comments?
Hah, yeah you can't put code in the comments. I didn't realise that xlswrite doesn't handle 2D data. You'll have to write it in two hits. One column, then the other. I don't ever use that function, but you should be able to work it out. If you have trouble, check the help for xlswrite. Also, if you prefer to read your data as integers instead of strings, use the format '%d%d' instead of '%s%s'. Columns will come back as a vector instead of an array.
It doesn't seem to work. I am getting all data in the same row, even when I am using different positions.
Please reply with your exact xlswrite call.

Sign in to comment.

Categories

Asked:

on 22 Mar 2012

Community Treasure Hunt

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

Start Hunting!