简体   繁体   中英

Matlab writematrix in Excel gives error: Name cannot be the same as built-in name

I want to copy an Excel file to a different path through Matlab and then write in it also using Matlab. Somehow I get the error: Name cannot be the same as built-in name. As I want to write multiple times in the file, I don't want to solve this problem manuelly each time, I want the code to run through without me having to do something constantly. Is there any way I can solve this problem all at once through code? Does this happen because I copy the Excel file first?

The code looks like this:

path_source_template1 = 'Blabla1\Template1.xlsx';

timestamp = datestr(now);
timestamp = strrep(timestamp, ':', '-');
timestamp = strrep(timestamp, ' ', '-');

path_output = fullfile('Blabla2\',timestamp);
mkdir(fullfile(path_output));

path_output_template1 = strcat(path_output,'\Template1.xlsx');

copyfile(path_source_template1,path_output_template1);

Then I want to write in the Template1.xlsx:

writematrix(test,path_output_template1,'Sheet','Test','Range','A1',UseExcel=true,AutoFitWidth=false);

Then I get this error: enter image description here

The input to the writematrix file uses the name, value format, so in this line:

writematrix(test,path_output_template1,'Sheet','Test','Range','A1',UseExcel=true,AutoFitWidth=false);

you should have:

..., 'Sheet','Test','Range','A1','UseExcel', true,'AutoFitWidth', false);

Disclaimer: I haven't tested this, but I'm fairly certain this will fix your problem.

The correct call to the writematrix would be:

writematrix(test,path_output_template1, 'Sheet','Test','Range','A1', 'UseExcel', true,'AutoFitWidth',false);

When writing datetime data to a spreadsheet file, you must set both 'PreserveFormat' and the 'UseExcel' Name-Value pair to true to preserve the existing cell formatting. You can check the documentation writematrix .

In order to answer to the error I tested the code locally in Matlab 2019b and works well setting the test variable in this example way: test = magic(5); .

Maybe the error could be in the data that you use in test variable or in that if you run the code iteratively very fast the path_output could exist, One way to improve this could be with a more accurate timestamp .

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