To import and export Excel data in MATLAB, you can use several built-in functions depending on your needs
To import and export Excel data in MATLAB, you can use several built-in functions depending on your needs. Below is a structured guide:
Importing Excel Data
- Using
readtable
(Recommended for Tabular Data):dataTable = readtable('filename.xlsx', 'Sheet', 'Sheet1', 'Range', 'A1:C10');
- Imports data into a table with column headers (if present).
- Specify
Sheet
andRange
for specific data regions.
- Using
xlsread
(Older Method, Numeric Data):[numericData, textData, rawData] = xlsread('filename.xlsx', 'Sheet1', 'A1:C10');
- Returns numeric data in
numericData
, text intextData
, and all data inrawData
.
- Returns numeric data in
- Using
readmatrix
/readcell
(Numeric or Cell Data):numericMatrix = readmatrix('filename.xlsx'); cellData = readcell('filename.xlsx');
- GUI Method (Import Tool):
- Use the Import Tool (UI) by typing
uiimport('filename.xlsx')
or clicking “Import Data” in the Home tab.
- Use the Import Tool (UI) by typing
Exporting Excel Data
- Using
writetable
(Recommended for Tables):writetable(dataTable, 'newfile.xlsx', 'Sheet', 'Results', 'WriteMode', 'replacefile');
- Exports a table (including headers) to Excel. Use
WriteMode
to overwrite or append.
- Exports a table (including headers) to Excel. Use
- Using
writematrix
/writecell
(Numeric/Cell Arrays):writematrix(numericMatrix, 'newfile.xlsx', 'Sheet', 2); writecell(cellData, 'newfile.xlsx');
- Using
xlswrite
(Older Method):xlswrite('newfile.xlsx', numericMatrix, 'Sheet1', 'A1');
Key Tips
- Sheets/Ranges: Specify
Sheet
by name (e.g., ‘Sheet1’) or index (e.g., 2). - Headers:
readtable
automatically detects headers. Use'VariableNamingRule','preserve'
to retain spaces. - Mixed Data: Use
readtable
orreadcell
for cells containing text/numbers. - Performance: For large files,
readtable
is faster thanxlsread
. - Compatibility: On macOS/Linux, Excel installation is not required for
readtable
/writetable
(they use different libraries).
Troubleshooting
- File Access: Ensure the Excel file is not open elsewhere.
- Missing Values: Use
TreatAsMissing
inreadtable
to handle placeholders likeNA
. - Formats: Use
detectImportOptions
to customize data types:opts = detectImportOptions('filename.xlsx'); opts = setvartype(opts, 'Column1', 'datetime'); % Set column type data = readtable('filename.xlsx', opts);
Example Workflow
% Import salesData = readtable('sales2023.xlsx', 'Sheet', 'Q4'); % Process data salesTotal = sum(salesData.Revenue); % Export results = table(salesTotal, 'VariableNames', {'TotalRevenue'}); writetable(results, 'results.xlsx', 'Sheet', 'Summary');
For more control, explore Spreadsheet Link to connect MATLAB with Excel macros