How to save tables to different sheets in one xlsx file?

조회 수: 77 (최근 30일)
Niya Bedzheva
Niya Bedzheva 2019년 9월 3일
댓글: FM 2022년 7월 13일
Hello everyone,
i have a for loop reading several files and doing some calculations for each of them. What i want to do is to save the results from every file in a seperate sheet on one excel file.
%% reading the files
files = dir('*.txt');
N=length(files);
for i=1:N
filename=files(i).name;
fid=fopen(filename);
data = textscan (fid, '%s %s %s %s %s %s %s %*s %*s %s %*s', 'headerLines', 2);
%%saving
R1=table (Time, beta, Sh, K, 'VariableNames' , {'Time', 'beta', 'Sh', 'K'});
F_xlsx=sprintf('results.xlsx');
writetable(R1,F_xlsx,'Sheet',[files(i).name]);
this is how i tried, but the it is filling the sheet only with the first file.
  댓글 수: 1
Andy
Andy 2019년 9월 3일
from the Matlab documentation "wrtitetable(T) writes table T to a comma delimited text file." As far as I am aware, this format doesn't support multiple sheets. I have used xlswrite when writing to Excel as you can define the sheet to be written to.

댓글을 달려면 로그인하십시오.

채택된 답변

Nicolas B.
Nicolas B. 2019년 9월 3일
Have you done a step-by-step execution of your code to be sure that there are multiple files read?
Looking at it like that, I would just remore the square brakets to the sheet name:
writetable(R1,F_xlsx,'Sheet',files(i).name);
Personnally, I'm using writematrix() the same way on different tables without any problem.
  댓글 수: 4
Niya Bedzheva
Niya Bedzheva 2019년 9월 3일
everything is perfect now. Thank you very much for the help! :)
FM
FM 2022년 7월 13일
I should have known better than to try exporting the CSV and writing VBA to import multiple files into different sheets within a common workbook. What a nightmare. This is a much more elegant solution, by orders of magnitude.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by