MATLAB: Retrieve data from a particualr row

txt to excel

I have attached a 'txt' file. If I open the txt file in Excel then I can see rows with the follwing
'Coal Consumption'
'Oil Consumption'
'Ngas Consumption'
'Biomass Consumption'
'Nuclear Fuel Consumption'
I need to retrieve the values in the adjacent column of 'Coal Consumption' , 'Oil Consumption' etc and export to an excel file. I need the output similar to the outfile_eg.xlsx attached.

Best Answer

Use this:
%% Initialize variables.
filename = 'C:\Users\Raj\Desktop\out_Denmark2030Alternative.txt'; % Put your text file path here
delimiter = '\t';
startRow = 28;
endRow = 32;
%% Format text:
% column1: text (%s) Consumption Type
% column2: double (%f) Qty
formatSpec = '%s%f%[^\n\r]';
%% Open the text file.
fileID = fopen(filename,'r');
%% Read columns of data according to format string.
Data = textscan(fileID, formatSpec, endRow-startRow+1, 'Delimiter', delimiter, 'HeaderLines', startRow-1, 'ReturnOnError', false);
%% Close the text file.
fclose(fileID);
%% Create output variable
A = table(Data{1:end-1}, 'VariableNames', {'ConsumptionType','Qty'});
A = table2cell(A); % Convert table to cell
A=A.';
%% Clear temporary variables
clearvars filename delimiter startRow endRow formatSpec fileID dataArray ans Data;
%% Write data to Excel file
xlswrite('Data.xls',A)