MATLAB の writetable​​関数で、既存のEx​celファイルの最終​列にテーブルを追記で​きますか

18 views (last 30 days)
MY
MY on 25 Apr 2023
Commented: MY on 28 Apr 2023
既存のExcelファイルの最終列の横に、別のテーブルデータを writetable 関数を使って追加することができますでしょうか。
'WriteMode'オプションを'append'にすることで最終行に追加できるのは確認できたのですが、列を追加する方法を見つけることができませんでした。
  2 Comments
Atsushi Ueno
Atsushi Ueno on 25 Apr 2023
下に追加されちゃいますね
writetable(table([10;20;30]),'Book1.xlsx','WriteMode','append');
readtable('Book1.xlsx')
ans = 6×3 table
Var1 Var2 Var3 ____ ____ ____ 1 4 7 2 5 8 3 6 9 10 NaN NaN 20 NaN NaN 30 NaN NaN
MY
MY on 26 Apr 2023
コメント有難うございます。
やはり下に追加されてしまいますよね。

Sign in to comment.

Accepted Answer

Kojiro Saito
Kojiro Saito on 26 Apr 2023
writetableのappendでは行の末尾にデータが追加されるので、末尾の列にデータを追加するにはExcelのシート全体を上書きするか、Rangeで書き込み位置を指定することで実現できます。
3列のExcelファイルに4列目をセルD1に追加した例です。
tblBefore = readtable('data.xlsx')
tblBefore = 3×3 table
Col1 Col2 Col3 ____ ____ ____ 1 1 1 2 2 2 3 3 3
Col4 = [1;2;3];
t = array2table(Col4);
writetable(t, 'data.xlsx', 'Range','D1')
tblAfter = readtable('data.xlsx')
tblAfter = 3×4 table
Col1 Col2 Col3 Col4 ____ ____ ____ ____ 1 1 1 1 2 2 2 2 3 3 3 3
  3 Comments
Kojiro Saito
Kojiro Saito on 27 Apr 2023
結構込み入っていますね。
例2の方法で、result.xlsxの列数をカウントしてその隣のセル番号に追記するコードサンプルを載せます。
C1 = readtable('ex.xlsx');
for col = 2:4 % '4'はサンプル数に応じて変更
Cc = C1(:,col) % ***
Cc1 = Cc(1,1);
Ccf0 = Cc - Cc1;
CcRatio = Ccf0 ./ Cc1;
Cc.Properties.VariableNames = {'#'};
Ccf0.Properties.VariableNames = {'deltaF'};
CcRatio.Properties.VariableNames = {'deltaF/F0'};
Tcol = [Cc Ccf0 CcRatio];
% 現在の列数をカウント
opts = detectImportOptions('result.xlsx');
colLength = length(opts.VariableNames); % 3 6 9 12...
% 書き初めのセル番号を作成
q = idivide(colLength, int16(26));
r = mod(colLength, 26);
if q == 0
cellPoint = 65+r; % D,E,...ZのASCIIコードの10進数番号
else
cellPoint = [65+q-1, 65+r]; % AA,AB,...AZ,BA,...,BZのASCIIコードの10進数番号
end
cellPointChar = [char(cellPoint), '1'];
% 書き初め列を指定して書き込み
writetable(Tcol, 'result.xlsx', 'Range', cellPointChar)
end
MY
MY on 28 Apr 2023
ご丁寧にありがとうございます。
行に追加は簡単ですが、列に追加するのは複雑なんですね。
無事に上記コードを基にデータ解析を行うことができました。
色々と応用できそうで、また新しいことをやりたくなってきました。
貴重なお時間を頂き、有難うございます。

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!