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

  1. Using readtable (Recommended for Tabular Data):
    matlab
    Copy
    dataTable = readtable('filename.xlsx', 'Sheet', 'Sheet1', 'Range', 'A1:C10');
    • Imports data into a table with column headers (if present).
    • Specify Sheet and Range for specific data regions.
  2. Using xlsread (Older Method, Numeric Data):
    matlab
    Copy
    [numericData, textData, rawData] = xlsread('filename.xlsx', 'Sheet1', 'A1:C10');
    • Returns numeric data in numericData, text in textData, and all data in rawData.
  3. Using readmatrix/readcell (Numeric or Cell Data):
    matlab
    Copy
    numericMatrix = readmatrix('filename.xlsx');
    cellData = readcell('filename.xlsx');
  4. GUI Method (Import Tool):
    • Use the Import Tool (UI) by typing uiimport('filename.xlsx') or clicking “Import Data” in the Home tab.

Exporting Excel Data

  1. Using writetable (Recommended for Tables):
    matlab
    Copy
    writetable(dataTable, 'newfile.xlsx', 'Sheet', 'Results', 'WriteMode', 'replacefile');
    • Exports a table (including headers) to Excel. Use WriteMode to overwrite or append.
  2. Using writematrix/writecell (Numeric/Cell Arrays):
    matlab
    Copy
    writematrix(numericMatrix, 'newfile.xlsx', 'Sheet', 2);
    writecell(cellData, 'newfile.xlsx');
  3. Using xlswrite (Older Method):
    matlab
    Copy
    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 or readcell for cells containing text/numbers.
  • Performance: For large files, readtable is faster than xlsread.
  • 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 in readtable to handle placeholders like NA.
  • Formats: Use detectImportOptions to customize data types:
    matlab
    Copy
    opts = detectImportOptions('filename.xlsx');
    opts = setvartype(opts, 'Column1', 'datetime'); % Set column type
    data = readtable('filename.xlsx', opts);

Example Workflow

matlab
Copy
% 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