MATLAB failing to read/edit Excel file on first-time code run

37 次查看(过去 30 天)
I am attempting to have MATLAB create and then modify an excel file, to format the cells so they're easier to read. Below is my code, which specifies what will fill cells A1 to B4, and then is meant to format them so that the cells fit the strings inside them (and center those strings). However, when I run the code, I receive the following error:
Error using Interface.000208DB_0000_0000_C000_000000000046/Open
Invoke Error, Dispatch Exception:
Source: Microsoft Excel
Description: Sorry, we couldn't find Output.xlsx. Is it possible it was moved, renamed or deleted?
Help File: xlmain11.chm
Help Context ID: 0
Error in readandwrite (line 113)
hWorkbook = hExcel.Workbooks.Open(outputfile);
This error only occurs on the first run of the code. After the code has created the file and is run a second time, the error stops occuring. However, I would like the formatting to be completed without needing a second pass of the code. As well, in previous iterations of my code, I did not have this issue—this is a new problem that has appeared. Thank you for the help.
outputfile = 'Output.xlsx';
worksheet = 'Sheet1';
sheetBasics = {
'Value' 'Description';
'1' 'Example 1';
'2' 'Example 2';
'3' 'Example 3';
};
xlswrite(outputfile,sheetBasics,worksheet);
% formatting the cells
hExcel = actxserver('Excel.Application');
hWorkbook = hExcel.Workbooks.Open(outputfile);
hWorksheet = hWorkbook.Sheets.Item(1);
hExcel.Cells.Select; % select entire spreadsheet
hExcel.Cells.EntireColumn.AutoFit; % auto fit all the columns
hExcel.Selection.VerticalAlignment = 2; % vertically align all columns
hExcel.Range('A1:A4').Select; % select first column
hExcel.Selection.HorizontalAlignment = 3; % center+vertical align first column
hExcel.Selection.VerticalAlignment = 2;
hExcel.Range('A1:B1').Select; % select first row
hExcel.Selection.HorizontalAlignment = 3; % center+vertical align first row
hExcel.Selection.VerticalAlignment = 2;
hExcel.Range('A1').Select; % Put "cursor" or active cell at A1, the upper left cell
hWorkbook.Save;
hWorkbook.Close;
hExcel.Quit;

采纳的回答

kei hin
kei hin 2023-8-8
try full path, like
hWorkbook = hExcel.Workbooks.Open([pwd,'\',outputfile])

更多回答(0 个)

标签

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by