0
0
MATLABdata~5 mins

Excel file reading and writing in MATLAB

Choose your learning style9 modes available
Introduction

Excel files store data in tables that are easy to read and edit. Reading and writing Excel files lets you work with this data inside MATLAB.

You want to import data from a spreadsheet to analyze it in MATLAB.
You need to save your MATLAB results into an Excel file to share with others.
You want to update or add data to an existing Excel file from MATLAB.
Syntax
MATLAB
data = readtable('filename.xlsx');

writetable(data, 'filename.xlsx');

readtable reads Excel data into a table format in MATLAB.

writetable writes a MATLAB table back to an Excel file.

Examples
This reads the entire Excel file 'data.xlsx' into a table called data.
MATLAB
data = readtable('data.xlsx');
This writes the table data into a new Excel file named 'output.xlsx'.
MATLAB
writetable(data, 'output.xlsx');
This reads data from the sheet named 'Sheet2' in the Excel file.
MATLAB
data = readtable('data.xlsx', 'Sheet', 'Sheet2');
This writes the table data to the sheet named 'Results' in the Excel file.
MATLAB
writetable(data, 'output.xlsx', 'Sheet', 'Results');
Sample Program

This program creates a small table with names and scores, writes it to an Excel file named 'sample.xlsx', then reads the data back and displays it.

MATLAB
filename = 'sample.xlsx';

% Create sample data
Names = {'Anna'; 'Ben'; 'Cara'};
Scores = [85; 92; 78];
T = table(Names, Scores);

% Write data to Excel file
writetable(T, filename);

% Read data back from Excel file
readData = readtable(filename);

disp('Data read from Excel file:');
disp(readData);
OutputSuccess
Important Notes

Make sure the Excel file is not open in another program when writing to it, or MATLAB may give an error.

You can specify sheet names and ranges to read or write specific parts of the Excel file.

Tables are a convenient way to handle Excel data because they keep column names and data together.

Summary

Use readtable to load Excel data into MATLAB as a table.

Use writetable to save MATLAB tables back to Excel files.

You can specify sheets and ranges to control what part of the Excel file you read or write.