简体   繁体   中英

Exporting data from cell to Excel file

Let's say I have a cell named data like this:

data{1} = vector1; 
data{2} = vector2; 
... 
data{n} = vectorn; 

All vectors (with numerical values) in data have the same 1xN size.

Now, I want to export this data file into an .xlsx document where each row is a vector and I want to label each column. The result should be something like this:

  label1         label2        ...       labelN

vector1(1,1)   vector1(1,2)    ...     vector1(1,N)

  ...              ...         ...         ...

vectorn(1,1)   vectorn(1,2)    ...     vectorn(1,N)

I tried to do this using:

n=10;
N=5;
for i=1:n
  data{i}=rand(1,N);
end
filename='test.xlsx';
xlswrite(filename,data)

but my .xlsx file comes with all the data from data in just one row. And I don't know how to do the labels.

Please help me.

This can be done using vertcat , num2cell , sprintf , strsplit and xlswrite as follows:

modified_data = num2cell(vertcat(data{:}));     % Converting 1xn cell into nxN cell

% Generating Column Headers as specified in the question
col_header = strsplit(sprintf('label%d ' , 1:N));
col_header = col_header(1:end-1);
% If N is not much high number (e.g; if N=5), you can input Column Headers as: 
% col_header = {'label1','label2','label3','label4','label5'};

filename='test.xlsx';                           % Name of the excel file to be written
xlswrite(filename,[col_header; modified_data]); % Writing the excel file

Its because you call rand(1,N) together in one cell ( data{i} ). For each value in its own cell you have to create a nxN matrix of cells, which is easiest done if you transfrom the entire matirx:

n=10;
N=5;
  data=rand(n,N);
  celldata=num2cell(data);
filename='test.xlsx';
xlswrite(filename,celldata);

otherwise you have to make two loops but thats not so great performancewise

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM