Reading excel with matlab

xlsread

(Not recommended) Read Microsoft
Excel
spreadsheet file

Syntax

Description

example

num = xlsread(filename)
reads the first worksheet in the Microsoft®
Excel®
spreadsheet workbook named filename and
returns the numeric data in a matrix.

num = xlsread(filename,sheet)
reads the specified worksheet.

example

num = xlsread(filename,xlRange)
reads from the specified range of the first worksheet in the workbook. Use
Excel range syntax, such as 'A1:C3'.

example

num = xlsread(filename,sheet,xlRange)
reads from the specified worksheet and range.

num = xlsread(filename,sheet,xlRange,'basic')
reads data from the spreadsheet in basic import mode. If your
computer does not have Excel for Windows® or if you are using MATLAB®
Online™
, xlsread automatically operates in
basic import mode, which supports XLS, XLSX, XLSM, XLTX,
and XLTM files.

If you do not specify all the arguments, use empty character vectors,
'' , as placeholders, for example, num =
xlsread(filename,'','','basic')
.

example

[num,txt,raw]
= xlsread(___)

additionally returns the text fields in cell array txt, and
both numeric and text data in cell array raw, using any of
the input arguments in the previous syntaxes.

___ = xlsread(filename,-1)
opens an Excel window to interactively select data. Select the worksheet, drag
and drop the mouse over the range you want, and click OK.
This syntax is supported only on Windows computers with Microsoft
Excel
software installed.

example

[num,txt,raw,custom]
= xlsread(filename,sheet,xlRange,'',processFcn)
,
where processFcn is a function handle, reads from the
spreadsheet, calls processFcn on the data, and returns the
final results as numeric data in array num. The
xlsread function returns the text fields in cell array
txt, both the numeric and text data in cell array
raw, and the second output from
processFcn in array custom. The
xlsread function does not change the data stored in the
spreadsheet. This syntax is supported only on Windows computers with Excel software.

Examples

collapse all

Read Worksheet Into Numeric Matrix

Create an Excel file named myExample.xlsx.

values = {1, 2, 3 ; 4, 5, 'x' ; 7, 8, 9};
headers = {'First','Second','Third'};
xlswrite('myExample.xlsx',[headers; values]);

Sheet1 of myExample.xlsx
contains:

   First    Second    Third
       1         2        3
       4         5    x    
       7         8        9

Read numeric data from the first worksheet.

filename = 'myExample.xlsx';
A = xlsread(filename)

Read Range of Cells

Read a specific range of data from the Excel file in the previous example.

filename = 'myExample.xlsx';
sheet = 1;
xlRange = 'B2:C3';

subsetA = xlsread(filename,sheet,xlRange)

Read Column

Read the second column from the Excel file in the first example.

filename = 'myExample.xlsx';

columnB = xlsread(filename,'B:B')

For better performance, include the row numbers in the range, such as
'B1:B3'.

Request Numeric, Text, and Raw Data

Request the numeric data, text data, and combined data from
the Excel file in the first example.

[num,txt,raw] = xlsread('myExample.xlsx')
num =
     1     2     3
     4     5   NaN
     7     8     9

txt = 
    'First'    'Second'    'Third'
    ''         ''          ''     
    ''         ''          'x'    

raw = 
    'First'    'Second'    'Third'
    [    1]    [     2]    [    3]
    [    4]    [     5]    'x'    
    [    7]    [     8]    [    9]

Execute a Function on a Worksheet

In the Editor, create a function to process data from a worksheet. In this
case, set values outside the range [0.2,0.8] to
0.2 or 0.8.

function [Data] = setMinMax(Data)

minval = 0.2; 
maxval = 0.8;
 
for k = 1:Data.Count
  v = Data.Value{k};
  if v > maxval
    Data.Value{k} = maxval;
  elseif v < minval
    Data.Value{k} = minval;
  end
end

In the Command Window, add random data to
myExample.xlsx.

A = rand(5);
xlswrite('myExample.xlsx',A,'MyData')

The worksheet named MyData contains values ranging from
0 to 1.

Read the data from the worksheet, and reset any values outside the range
[0.2,0.8]. Specify the sheet name, but use
'' as placeholders for the
xlRange and 'basic'
inputs.

trim = xlsread('myExample.xlsx','MyData','','',@setMinMax);

Request Custom Output

Execute a function on a worksheet and display the custom
index output.

In the Editor, modify the function setMinMax from the
previous example to return the indices of the changed elements (custom
output).

function [Data,indices] = setMinMax(Data)

minval = 0.2; 
maxval = 0.8;
indices = [];
 
for k = 1:Data.Count
  v = Data.Value{k};
  if v > maxval
    Data.Value{k} = maxval;
    indices = [indices k];
  elseif v < minval
    Data.Value{k} = minval;
    indices = [indices k];
  end  
end

Read the data from the worksheet MyData, and request
the custom index output, idx.

[trim,txt,raw,idx] = xlsread('myExample.xlsx',...
    'MyData','','',@setMinMax);

Input Arguments

collapse all

filenameFile name
character vector | string

File name, specified as a character vector or a string. If you do not
include an extension, xlsread searches for a file with
the specified name and a supported Excel extension. xlsread can read data saved in
files that are currently open in Excel for Windows.

Example: 'myFile.xlsx' or
"myFile.xlsx"

Data Types: char | string

sheetWorksheet
character vector | string | positive integer

Worksheet, specified as one of the following:

  • Character vector or string that contains the worksheet name. The
    name cannot contain a colon (:). To determine the
    names of the sheets in a spreadsheet file, use
    xlsfinfo. For XLS files in
    basic mode, sheet is case
    sensitive.

  • Positive integer that indicates the worksheet index. This option
    is not supported for XLS files in basic
    mode.

Data Types: char | string | single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

xlRangeRectangular range
character vector | string

Rectangular range, specified as a character vector or a string.

Specify xlRange using two opposing corners that define
the region to read. For example, 'D2:H4' represents the
3-by-5 rectangular region between the two corners D2 and
H4 on the worksheet. The xlRange
input is not case sensitive, and uses Excel A1 reference style (see Excel help).

Range selection is not supported when reading XLS files in
basic mode. In this case, use ''
in place of xlRange.

If you do not specify sheet, then
xlRange must include both corners and a colon
character, even for a single cell (such as 'D2:D2').
Otherwise, xlsread interprets the input as a worksheet
name (such as 'sales' or 'D2').

If you specify sheet, then xlRange:

  • Does not need to include a colon and opposite corner to
    describe a single cell.

  • Can refer to a named range that you defined in the Excel file (see the Excel help).

When the specified xlRange overlaps merged cells:

  • On Windows computers with Excel, xlsread expands the range to
    include all merged cells.

  • On computers without Excel for Windows, xlsread returns data for the
    specified range only, with empty or NaN
    values for merged cells.

Data Types: char | string

'basic'Flag to request reading in basic mode
character vector | string

Flag to request reading in basic mode, specified as the
character vector or a string, 'basic'.

basic mode is the default for computers without
Excel for Windows. In basic mode,
xlsread:

  • Reads XLS, XLSX, XLSM, XLTX, and XLTM files only.

  • Does not support an xlRange input when reading
    XLS files. In this case, use '' in place of
    xlRange.

  • Does not support function handle inputs.

  • Imports all dates as Excel serial date numbers. Excel serial date numbers use a different reference date
    than MATLAB date numbers.

Data Types: char | string

processFcnHandle to a custom function
function handle

Handle to a custom function. This argument is supported only on
Windows computers with Excel software. xlsread reads from the
spreadsheet, executes your function on a copy of the data, and returns the
final results. xlsread does not change the data stored in
the spreadsheet.

When xlsread calls the custom function, it passes a
range interface from the Excel application to provide access to the data. The custom function
must include this interface both as an input and output argument. (See Execute a Function on a Worksheet)

Example: @myFunction

Output Arguments

collapse all

num — Numeric data
matrix

Numeric data, returned as a matrix of double values.
The array does not contain any information from header lines, or from outer
rows or columns that contain nonnumeric data. Text data in inner spreadsheet
rows and columns appear as NaN in the
num output.

txt — Text data
cell array

Text data, returned as a cell array. Numeric values in inner spreadsheet
rows and columns appear as empty character vectors, '',
in txt.

For XLS files in basic import mode, the
txt output contains empty character vectors,
'', in place of leading columns of numeric data that
precede text data in the spreadsheet. In all other cases,
txt does not contain these additional columns.

Undefined values (such as '#N/A') appear in the
txt output as '#N/A', except for
XLS files in basic mode.

raw — Numeric and text data
cell array

Numeric and text data from the worksheet, returned as a cell array.

On computers with Excel for Windows, undefined values (such as '#N/A') appear
in the raw output as 'ActiveX
VT_ERROR:'
. For XLSX, XLSM, XLTX, and XLTM files on other
computers or in MATLAB
Online
, undefined values appear as '#N/A'.

custom — Second output of the function corresponding to processFcn
defined by the function

Second output of the function corresponding to
processFcn. The value and data type of
custom are determined by the function.

Limitations

  • xlsread reads only 7-bit ASCII characters.

  • xlsread does not support non-contiguous ranges.

  • If your computer does not have Excel for Windows or if you are using MATLAB
    Online
    , xlsread automatically operates in
    basic import mode.

  • On Linux® and Mac platforms, xlsread cannot open spreadsheet
    files written by the writetable function.

Algorithms

  • xlsread imports formatted text representing dates (such as
    '10/31/96'), except when importing in
    basic mode.

Version History

Introduced before R2006a

expand all

R2019a: xlsread is not recommended

xlsread is not recommended. Use readtable, readmatrix, or readcell instead. There are no plans to remove
xlsread.

Starting in R2019a, import spreadsheet data as a table, a matrix, or a cell array
by using readtable, readmatrix, or
readcell respectively. The readtable,
readmatrix, and readcell functions have
these advantages over the xlsread function:

  • Better cross-platform support and performance

  • Automatic detection of data format and types

  • Ability to use import options to control the data import process,
    including the handling of errors and missing data

This table shows typical usages of xlsread and how to update
your code to use readtable, readmatrix, or
readcell instead.

Not Recommended

Recommended

Read spreadsheet data as a matrix using
xlsread:

M = xlsread(filename)

Read spreadsheet data as a
table:

T = readtable(filename)

However,
to continue reading your data as a matrix,
use:

M = readmatrix(filename)

Read spreadsheet data as a cell array using
xlsread:

[~,~,C] = xlsread(filename)

Import spreadsheet data as a
table:

T = readtable(filename)

However,
to continue importing your data as a cell array,
use:

C = readcell(filename)

Read a specific sheet and range as a matrix using
xlsread:

M = xlsread(filename,sheet,range)

Read a specific sheet and range as a
table:

T = readtable(filename,'Sheet',sheet,'Range',range)

However,
to continue reading your data as a matrix,
use:

M = readmatrix(filename,'Sheet',sheet,'Range',range)

Read a specific sheet and range as a cell array using
xlsread:

[~,~,C] = xlsread(filename,sheet,range)

Read a specific sheet and range as a
table:

T = readtable(filename,'Sheet',sheet,'Range',range)

However,
to continue reading your data as a cell
array:

C = readcell(filename,'Sheet',sheet,'Range',range)

(Не рекомендуемый)
файл электронной таблицы Read Microsoft Excel

Синтаксис

Описание

пример

num = xlsread(filename) читает первый рабочий лист в Microsoft® Excel® рабочая книга электронной таблицы под названием filename и возвращает числовые данные в матрице.

num = xlsread(filename,sheet) читает заданный рабочий лист.

пример

num = xlsread(filename,xlRange) чтения от заданной области первого рабочего листа в рабочей книге. Используйте синтаксис области значений Excel, такой как 'A1:C3'.

пример

num = xlsread(filename,sheet,xlRange) чтения из заданного рабочего листа и области значений.

num = xlsread(filename,sheet,xlRange,'basic') считывает данные из электронной таблицы в basic импортируйте режим. Если ваш компьютер не имеет Excel для Windows® или если вы используете MATLAB® Online™, xlsread автоматически действует в basic импортируйте режим, который поддерживает XLS, XLSX, XLSM, XLTX и файлы XLTM.

Если вы не задаете все аргументы, используйте пустые символьные вектора, '' , как заполнители, например, num = xlsread(filename,'','','basic').

пример

[num,txt,raw]
= xlsread(___)
дополнительно возвращает текстовые поля в массиве ячеек txt, и и числовые данные и текстовые данные в массиве ячеек raw, использование любого из входных параметров в предыдущих синтаксисах.

___ = xlsread(filename,-1) открывает окно Excel, чтобы в интерактивном режиме выбрать данные. Выберите рабочий лист, перетащите мышью мышь в области значений, которую вы хотите и нажимаете OK. Этот синтаксис поддерживается только на компьютерах Windows с установленным программным обеспечением Microsoft Excel.

пример

[num,txt,raw,custom]
= xlsread(filename,sheet,xlRange,'',processFcn)
, где processFcn указатель на функцию, чтения из электронной таблицы, processFcn вызовов на данных, и возвращает конечные результаты как числовые данные в массиве num. xlsread функция возвращает текстовые поля в массиве ячеек txt, и числовые данные и текстовые данные в массиве ячеек raw, и второй выход от processFcn в массиве custom. xlsread функция не изменяет данные, хранимые в электронной таблице. Этот синтаксис поддерживается только на компьютерах Windows с программным обеспечением Excel.

Примеры

свернуть все

Чтение рабочего листа в числовую матрицу

Создайте файл с именем Excel myExample.xlsx.

values = {1, 2, 3 ; 4, 5, 'x' ; 7, 8, 9};
headers = {'First','Second','Third'};
xlswrite('myExample.xlsx',[headers; values]);

Sheet1 из myExample.xlsx содержит:

   First    Second    Third
       1         2        3
       4         5    x    
       7         8        9

Считайте числовые данные из первого рабочего листа.

filename = 'myExample.xlsx';
A = xlsread(filename)

Чтение области значений ячеек

Считайте определенную область значений данных из файла Excel в предыдущем примере.

filename = 'myExample.xlsx';
sheet = 1;
xlRange = 'B2:C3';

subsetA = xlsread(filename,sheet,xlRange)

Чтение столбца

Считайте второй столбец из файла Excel в первом примере.

filename = 'myExample.xlsx';

columnB = xlsread(filename,'B:B')

Для лучшей эффективности включайте номера строк в область значений, такие как 'B1:B3'.

Числовой запрос, текст и необработанные данные

Запросите числовые данные, текстовые данные и объединенные данные из файла Excel в первом примере.

[num,txt,raw] = xlsread('myExample.xlsx')
num =
     1     2     3
     4     5   NaN
     7     8     9

txt = 
    'First'    'Second'    'Third'
    ''         ''          ''     
    ''         ''          'x'    

raw = 
    'First'    'Second'    'Third'
    [    1]    [     2]    [    3]
    [    4]    [     5]    'x'    
    [    7]    [     8]    [    9]

Выполнение функции на рабочем листе

В Редакторе создайте функцию, чтобы обработать данные из рабочего листа. В этом случае установите значения вне области значений [0.2,0.8] к 0.2 или 0.8.

function [Data] = setMinMax(Data)

minval = 0.2; 
maxval = 0.8;
 
for k = 1:Data.Count
  v = Data.Value{k};
  if v > maxval
    Data.Value{k} = maxval;
  elseif v < minval
    Data.Value{k} = minval;
  end
end

В Командном окне добавьте случайные данные в myExample.xlsx.

A = rand(5);
xlswrite('myExample.xlsx',A,'MyData')

Рабочий лист под названием MyData содержит значения в пределах от от 0 до 1.

Считайте данные из рабочего листа и сбросьте любые значения вне области значений [0.2,0.8]. Задайте имя листа, но используйте '' как заполнители для xlRange и 'basic' входные параметры.

trim = xlsread('myExample.xlsx','MyData','','',@setMinMax);

Запрос пользовательского Вывода

Выполните функцию на рабочем листе и отобразите пользовательский индекс выход.

В Редакторе измените функциональный setMinMax от предыдущего примера, чтобы возвратить индексы измененных элементов (пользовательский выход).

function [Data,indices] = setMinMax(Data)

minval = 0.2; 
maxval = 0.8;
indices = [];
 
for k = 1:Data.Count
  v = Data.Value{k};
  if v > maxval
    Data.Value{k} = maxval;
    indices = [indices k];
  elseif v < minval
    Data.Value{k} = minval;
    indices = [indices k];
  end  
end

Считайте данные из рабочего листа MyData, и запросите пользовательский индекс выход, idx.

[trim,txt,raw,idx] = xlsread('myExample.xlsx',...
    'MyData','','',@setMinMax);

Входные параметры

свернуть все

filename FileName
вектор символов | строка

Имя файла в виде вектора символов или строки. Если вы не включаете расширение, xlsread поиски файла с указанным именем и поддерживаемым расширением Excel. xlsread может считать данные, сохраненные в файлах, которые в настоящее время открыты в Excel для Windows.

Пример: 'myFile.xlsx' или "myFile.xlsx"

Типы данных: char | string

sheetРабочий лист
вектор символов | представляет в виде строки | положительное целое число

Рабочий лист в виде одного из следующего:

  • Вектор символов или строка, которая содержит имя рабочего листа. Имя не может содержать двоеточие (:). Чтобы определить имена листов в файле электронной таблицы, используйте xlsfinfo. Для файлов XLS в basic режим, sheet является чувствительным к регистру.

  • Положительное целое число, которое указывает на индекс рабочего листа. Эта опция не поддерживается для файлов XLS в basic режим.

Типы данных: char | string | single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

xlRangeПрямоугольная область значений
вектор символов | строка

Прямоугольная область значений в виде вектора символов или строки.

Задайте xlRange использование двух противостоящих углов, которые задают область, чтобы читать. Например, 'D2:H4' представляет прямоугольную область 3 на 5 между этими двумя углами D2 и H4 на рабочем листе. xlRange вход не является чувствительным к регистру, и использует стиль ссылки Excel A1 (см. справку Excel).

Выбор области значений не поддерживается при чтении файлов XLS в basic режим. В этом случае используйте '' вместо xlRange.

Если вы не задаете sheet, затем xlRange должен включать оба угла и символ двоеточия, даже для отдельной ячейки (такие как 'D2:D2'). В противном случае, xlsread интерпретирует вход как имя рабочего листа (такое как 'sales' или 'D2').

Если вы задаете sheet, затем xlRange:

  • Не должен включать двоеточие и противоположный угол, чтобы описать отдельную ячейку.

  • Может относиться к именованной области значений, которую вы задали в файле Excel (см. справку Excel).

Когда заданный xlRange объединенные ячейки перекрытий:

  • На компьютерах Windows с Excel, xlsread расширяет область значений, чтобы включать все объединенные ячейки.

  • На компьютерах без Excel для Windows, xlsread возвращает данные для заданной области только, с пустым или NaN значения для объединенных ячеек.

Типы данных: char | string

'basic'Отметьте, чтобы запросить чтение в basic режим
вектор символов | строка

Отметьте, чтобы запросить чтение в basic режим в виде вектора символов или строки, 'basic'.

basic режим является значением по умолчанию для компьютеров без Excel для Windows. В basic режим, xlsread:

  • Чтения XLS, XLSX, XLSM, XLTX и файлы XLTM только.

  • Не поддерживает xlRange введите при чтении файлов XLS. В этом случае используйте '' вместо xlRange.

  • Не делает входных параметров указателя функции поддержки.

  • Импорт все даты как Excel последовательные числа даты. Excel последовательные числа даты использует различную ссылочную дату, чем числа даты MATLAB.

Типы данных: char | string

processFcnОбработайте к пользовательской функции
указатель на функцию

Обработайте к пользовательской функции. Этот аргумент поддерживается только на компьютерах Windows с программным обеспечением Excel. xlsread чтения из электронной таблицы, выполняет вашу функцию на копии данных и возвращает конечные результаты. xlsread не изменяет данные, хранимые в электронной таблице.

Когда xlsread вызывает пользовательскую функцию, она передает интерфейс диапазона из приложения Excel, чтобы обеспечить доступ к данным. Пользовательская функция должна включать этот интерфейс оба как аргумент ввода и вывода. (См., Выполняют Функцию на Рабочем листе),

Пример: @myFunction

Выходные аргументы

свернуть все

num — Числовые данные
матрица

Числовые данные, возвращенные как матрица double значения. Массив не содержит информации от линий заголовка, или из внешних строк или столбцов, которые содержат нечисловые данные. Текстовые данные во внутренних строках и столбцах электронной таблицы появляются как NaN в num вывод .

txt — Текстовые данные
cellArray

Текстовые данные, возвращенные как массив ячеек. Числовые значения во внутренних строках и столбцах электронной таблицы появляются как пустые символьные вектора, '', в txt.

Для файлов XLS в basic импортируйте режим, txt выведите содержит пустые символьные вектора, '', вместо ведущих столбцов числовых данных, которые предшествуют текстовым данным в электронной таблице. Во всех других случаях, txt не содержит эти дополнительные столбцы.

Неопределенные значения (такие как '#N/A') появитесь в txt выведите как '#N/A', за исключением файлов XLS в basic режим.

raw — Числовой и текстовые данные
cellArray

Числовой и текстовые данные из рабочего листа, возвращенного как массив ячеек.

На компьютерах с Excel для Windows, неопределенные значения (такие как '#N/A') появитесь в raw выведите как 'ActiveX VT_ERROR:'. Для XLSX, XLSM, XLTX и файлов XLTM на других компьютерах или в MATLAB Online, неопределенные значения появляются как '#N/A'.

custom — Второй выход функции, соответствующей processFcn
заданный функцией

Второй выход функции, соответствующей processFcn. Значение и тип данных custom определяются функцией.

Ограничения

  • xlsread чтения только 7-битные символы ASCII.

  • xlsread не поддерживает области значений, состоящие из нескольких несмежных участков.

  • Если ваш компьютер не имеет Excel для Windows или если вы используете MATLAB Online, xlsread автоматически действует в basic импортируйте режим.

  • На Linux® и платформы Mac, xlsread не может открыть файлы электронной таблицы, записанные writetable функция.

Алгоритмы

  • xlsread форматированный текст импорта, представляющий даты (такие как '10/31/96'), кроме тех случаев, когда импорт в basic режим.

Вопросы совместимости

развернуть все

xlsread не рекомендуется

Не рекомендуемый запуск в R2019a

xlsread не рекомендуется. Использование readtable, readmatrix, или readcell вместо этого. Нет никаких планов удалить xlsread.

Начиная в R2019a, импортируйте данные об электронной таблице как таблицу, матрицу или массив ячеек при помощи readtable, readmatrix, или readcell соответственно. readtable, readmatrix, и readcell функции имеют эти преимущества перед xlsread функция:

  • Лучше кросс-платформенная поддержка и эффективность

  • Автоматическое обнаружение формата данных и типов

  • Способность использовать настройки импорта, чтобы управлять данными импортирует процесс, включая обработку ошибок и недостающих данных

Эта таблица показывает типичные использования xlsread и как обновить ваш код, чтобы использовать readtable, readmatrix, или readcell вместо этого.

Не рекомендуемый

Рекомендуемый

Считайте данные об электронной таблице как матрицу с помощью xlsread:

M = xlsread(filename)

Считайте данные об электронной таблице как таблицу:

T = readtable(filename)

Однако, чтобы продолжить считывать ваши данные как матрицу, используйте:

M = readmatrix(filename)

Считайте данные об электронной таблице как массив ячеек с помощью xlsread:

[~,~,C] = xlsread(filename)

Импортируйте данные об электронной таблице как таблицу:

T = readtable(filename)

Однако, чтобы продолжить импортировать ваши данные как ячейку arrary, используйте:

C = readcell(filename)

Считайте определенный лист и область значений как матрица с помощью xlsread:

M = xlsread(filename,sheet,range)

Считайте определенный лист и область значений как таблица:

T = readtable(filename,'Sheet',sheet,'Range',range)

Однако, чтобы продолжить считывать ваши данные как матрицу, используйте:

M = readmatrix(filename,'Sheet',sheet,'Range',range)

Считайте определенный лист и область значений как массив ячеек с помощью xlsread:

[~,~,C] = xlsread(filename,sheet,range)

Считайте определенный лист и область значений как таблица:

T = readtable(filename,'Sheet',sheet,'Range',range)

Однако продолжать считывать ваши данные как массив ячеек:

C = readcell(filename,'Sheet',sheet,'Range',range)

Представлено до R2006a

This article is a quick tutorial on using the xlsread MATLAB command to import data from an Excel file into MATLAB. Specifically, you’ll learn to:

  • Extract data from Excel in MATLAB
  • Remove irrelevant content from your extract
  • Import data from a specific sheet
  • Select the Excel file to read
  • Extract different formats

How to Extract Data from Excel in MATLAB

Xlsread Basic Syntax

Here’s the basic syntax to import data from Excel into MATLAB:

[numbers text textAndNumbers] = xlsread(excelFileName)
  • numbers: numbers contained in your Excel file.
  • text: text contained in your Excel file.
  • textAndNumbers: text and numbers contained in your Excel file.

Xlsread MATLAB Example

First, let’s look at some details about how this works through an actual example. Let’s say I have the following Excel file named “excelFile.xlsx:”

Example of reading an Excel file using xlsread

Then, applying the previous basic syntax to read it, we get:

excelFileName = 'excelFile.xlsx';
[numbers text textAndNumbers] = xlsread(excelFileName);

So, let’s examine the outputs of the xlsread MATLAB command:
numbers of the Excel file exctracttext of the Excel file exctracttext and numbers of the Excel file exctract
As you can see, the three outputs are not of the same data type:

  • “numbers” is an array: this means that you can access the content of an element using parentheses: numbers(i)
  • “text” is a cell array: this means that you can access the content of a cell using braces: text{i}
  • “numbersAndText” is a cell array: this means that you can access the content of a cell using braces: numbersAndText{i}

Remove Irrelevant Content from Your Extract

  • Notice that for the “numbers” variable, the first and last rows have been removed, and the text has been replaced by “NaN” value. You can get rid of the “NaN” values with the following:
    numbers = numbers(~isnan(numbers)); % delete numbers that are not "NaN"

    The “numbers” variable then becomes:
    isnan MATLAB command example

  • The numbers contained in the “text” variable have been replaced by empty cells. You can get rid of the empty cells with the following:
    text = text(~cellfun('isempty', text)); % delete empty cells

    The “text” variable then becomes:
    remove empty cell from Excel file extract

Import Data from a Specific Sheet

What If the Content Is in Another Sheet?

Let’s use the previous Excel file “excelFile.xlsx” with the content on a sheet named “Sheet1” (which is the default name of a sheet if you create an Excel file).
Moreover, if you add a sheet to the Excel file, the name of the sheet will be “Sheet2.” So, let’s do that and move the first sheet (with the previous content) to the right of the second sheet and save the file:
finding a specific sheet using xlsread MATLAB command

Then, we’ll apply the xlsread MATLAB command as we did previously:

excelFileName = 'excelFile.xlsx';
[numbers text textAndNumbers] = xlsread(excelFileName);

By default, xlsread will read the sheet located at the very left of the Excel file, namely “Sheet2.”

xlsread extract of an empty sheet
Since “Sheet2” is empty, it makes sense that the extracted content is empty. So, how do you read “Sheet1”?

Finding a Sheet

First, there are two ways to specify the sheet to read using the xlsread MATLAB command:

  1. Using the number of the sheet:
    [numbers text textAndNumbers] = xlsread(excelFileName, sheetNumber);

    The number of the sheet is “2” here because we want to read the second sheet (counting from the left). So, giving the “sheetNumber” variable the value “1” is equivalent to not using the second argument of the xlsread MATLAB command. Here’s how to extract the desired sheet:

    sheetNumber = 2; % second sheet counting from the left
    excelFileName  = 'excelFile.xlsx';
    [numbers text textAndNumbers] = xlsread(excelFileName, sheetNumber);
  2. Using the name of the sheet:
    [numbers text textAndNumbers] = xlsread(excelFileName, sheetName);

    The sheet name in that example is “Sheet1,” so you can use it as the second argument if you want to extract the second sheet:

    sheetName = 'Sheet1';
    excelFileName  = 'excelFile.xlsx';
    [numbers text textAndNumbers] = xlsread(excelFileName, sheetName);

In both cases, if the sheet number or the sheet name you’re referring to doesn’t exist, you’ll get the following error:
Error in xlsread: Worksheet not found

Specific Problems and Solutions

Ask the User to Select an Excel File

Using the uigetfile MATLAB command, you can ask the user to find and select the desired excel file to be read:

[fileName, pathName] = uigetfile({'*.xlsx';'*.xls'}, 'Choose an Excel file');

You can then use the “fileName” and the “pathName” (respectively the name of the selected file and its location) to read your Excel file.
There are 2 ways of doing that:

  • Moving to the file’s location:
    [fileName, pathName] = uigetfile({'*.xlsx';'*.xls'}, 'Choose an Excel file');
    currentFolder = pwd; % save the current location
    cd(pathName)
    [numbers text textAndNumbers] = xlsread(fileName)
    cd(currentFolder);

    We use the pwd MATLAB command to save the current location from before, move to the Excel file’s location, perform the extraction, and move back to the initial location.

  • Specifying the location:
    [fileName, pathName] = uigetfile({'*.xlsx';'*.xls'}, 'Choose an Excel file');
    fullFileExcelFile = fullfile(pathName, fileName); % create the path to the Excel file
    [numbers text textAndNumbers] = xlsread(fullFileExcelFile);

    fullfile creates the path by adding ‘/’ or ‘’ between the file name and the path name (you could do it yourself with something like [pathName ‘/’ fileName], but this can be a little bit trickier depending on whether you use a UNIX or Windows platform).

Be Careful About the Format of the Cells You’re Extracting

First, if the numbers contained in your Excel file are formatted as strings, you’ll get a cell array when extracting. For example, by adding a single quotation mark to the left of every number in the Excel file “excelFile.xlsx” that we’ve used previously, we are formatting them as strings:Use numbers as string for the Excel file extractAnd if we import the data from the Excel file now, we get:
xlsread MATLAB extract empty numbersxlsread MATLAB text extract for string numbersxlsread MATLAB text and numbers extract for string numbers
Since the numbers have been formatted as strings in the Excel file, there are no numbers anymore, the “numbers” variable is empty and the “text” and “textAndNumbers” variables have become identical.

The Empty Cell Issue

If you have empty cells in your Excel file before the first row, the xlsread MATLAB command will get rid of them. This is a problem if you want to write the content back to the Excel file (e.g. to modify a value) because you won’t be able to know where to write it.

Unfortunately, there is no easy way to get that information using xlsread. If you have this issue, you can refer to this article for a workaround: https://realtechnologytools.com/matlab-row-number/

Key takeaways:

  • To read an Excel file, use:
    [numbers text textAndNumbers] = xlsread(excelFileName);
    • numbers: array of the numbers in the file, access an element using numbers(i)
    • text: cell array of the text in the file, access an element using text{i}
    • textAndNumbers: cell array of the text and numbers in the file, access an element using textAndNumbers{i}
  • To remove irrelevant values from your extract, use:
    numbers = numbers(~isnan(numbers)); % delete numbers that are "NaN"
    text = text(~cellfun('isempty', text)); % delete empty cells
  • To import a specific sheet in MATLAB, use:
    [numbers text textAndNumbers] = xlsread(excelFileName, sheetName); % use the sheet name
    [numbers text textAndNumbers] = xlsread(excelFileName, sheetNumber); % use the sheet number
  • There are 2 ways to ask the user to select an Excel file and read it:
    1. By moving to the file’s location:
      [fileName, pathName] = uigetfile({'*.xlsx';'*.xls'}, 'Choose an Excel file');
      currentFolder = pwd; % save the current location
      cd(pathName)
      [numbers text textAndNumbers] = xlsread(fileName)
      cd(currentFolder);
    2. By specifying the location:
      [fileName, pathName] = uigetfile({'*.xlsx';'*.xls'}, 'Choose an Excel file');
      fullFileExcelFile = fullfile(pathName, fileName); % create the path to the Excel file
      [numbers text textAndNumbers] = xlsread(fullFileExcelFile);
  • If the numbers in your Excel file are formatted as strings (e.g. using a single quotation mark at the left of a number in the Excel file), then they will be extracted in the “text” variable rather than in the “numbers” variable.

You can find more information about the xlsread MATLAB function in the MathWorks documation: https://fr.mathworks.com/help/matlab/ref/xlsread.html

If you want to learn more about the practical tips that helped me stop wasting time doing mindless work (such as working with Excel files and writing reports) I wrote a small reference book about it:

xlsread Matlab

Introduction of xlsread Matlab

‘xls’ command is used in Matlab to import and export excel files into Matlab. We can create the excel files by using this command as well as we can read the excel files by using this commands. there are two operation in Matlab one is to create excel files and other is to read or open excel files. These commands are xlsread and xlswrite. Xlsread command is used to read or open the existing excel files in Matlab. Xlswrite command is used to write or create excel files in Matlab.by using xlswrite command we can also modify content of existing excel files. This command improves the adaptability of Matlab language by accessing data in other formats.

Syntax:

xlsread (filename)
xlsread (filename, parameters list)
xlsread (filename, [data])
xlsread (filename, sheet name)
xlsread (filename, range for columns or row)

How does xlsread Work in Matlab?

To read any excel file in Matlab first we need to create that file with some data in to it. There are various ways to write and read the excel files. These files can be written by sing parameter list, direct data, by giving sheet name, or by giving a range of the columns or rows.

Steps to read excel file in Matlab –

  • Clear workspace
  • Declare and assign data
  • Write into excel file by using ‘xlsread’ syntax( xlswrite (filename,[data])
  • Declare variable to read a file
  • Use xlsread read command by using syntax. ( xlsread (filename ) ).

Examples of xlsread Matlab

Following are the examples are given below:

Example #1

In this example, excel file is ‘abc.xlsx’ and data added to the file is [ 13 ,42, 53 ]. So it create one excel file in current directory.

Matlab Editor Command window
Clc ;

xlswrite(‘abc.xlsx ‘,[13, 42, 53])

xlsread (‘ abc.xlsx ‘)

ans =

13    42    53

Output:

xlsread Matlab-1.1

Example #2

In this example input data is declared by using another variable, which is ‘data’ (data= [3 4  7 7;4 3 2 2;4 56 78 32]) . Data is written in ‘file1’.

Matlab Editor Command Window
Clc ;

Data = [3 4  7 7 ; 4 3 2 2 ; 4 56 78 32]

xlswrite(‘ file1.xlsx ‘, data)

xlsread (‘ file1.xlsx ’)

data =

3     4     7     7

4     3     2     2

4    56    78    32

ans =

3     4     7     7

4     3     2     2

4    56    78    32

Output:

xlsread Matlab-1.2

Example #3

In this example input data is declared by using another two variables,  which is ‘data’ (data1= [3 54  47 ;4 33 22; 56 7 42;43 7 1] and data2=[56 4 2 ; 5 4 2; 67 4 1;1 01 1]. Data is written in ‘file2’.

Matlab Editor Command Window
Clc ;

data1= [3 54  47 ; 4 33 22; 56 7 42 ; 43 7 1]

data2 = [56 4 2 ; 5 4 2 ; 67 4 1 ; 1 01 1]

xlswrite(‘ file2.xlsx ‘ , [data1 ; data2])

xlsread(‘ file2.xlsx ‘)

data1 =

3    54    47

4    33    22

56     7    42

43     7     1

data2 =

56     4     2

5     4     2

67     4     1

1     1     1

ans =

3    54    47

4    33    22

56     7    42

43     7     1

56     4     2

5     4     2

67     4     1

1     1     1

Output:

xlsread Matlab-1.3

Example #4

In this example input data is declared by using another two variables ,  which is ‘data’ (data1= [3 54  47 ;4 33 22; 56 7 42;43 7 1]and data2=[56 4 2 ; 5 4 2; 67 4 1;1 01 1]). Data is written in ‘file1’.to read the file we use range function. By giving range to the specific file we can display only important data.

Matlab Editor Command Window
Clc ;

data1 = [3 54  47 ;4 33 22; 56 7 42;43 7 1]

data2 = [56 4 2 ; 5 4 2 ; 67 4 1 ; 1 01 1]

xlswrite(‘file2.xlsx’,[data1 ; data2])

r = ‘ A3 : B2 ‘

a = xlsread(‘file2.xlsx’, r )

data1 =

3    54    47

4    33    22

56     7    42

43     7     1

data2 =

56     4     2

5     4     2

67     4     1

1     1     1

r =

A3:B2

a =

4    33

56     7

Output:

Output-1.4

Example #5

In this example input data is declared by using another two variables , which is ‘data’ (data1= [3 54 43 47 ; 4 33 32 22 ; 56 5 7 42 ; 11 23 7 1] and data2 =[56 4 2 4 ;0 5 4 2; 67 1 4 1;1 01 1 1 ]). Data is written in ‘file3’.to read the file we use range function. By giving range to the specific file we can display only important data. Here start range value and end range value is same to we can display only specific row or column by using this method.

Matlab Editor Command Window
clc;

data1= [3 54 43 47 ;4 33  32 22; 56 5  7 42;11 23 7 1]

data2=[56 4 2 4 ;0 5 4 2; 67 1 4 1;1 01  1 1]

xlswrite(‘file3.xlsx’,[data1;data2])

r=’C:C’

a=xlsread(‘file3.xlsx’,r)

data1 =

3    54    43    47

4    33    32    22

56     5     7    42

11    23     7     1

data2 =

56     4     2     4

0     5     4     2

67     1     4     1

1     1     1     1

r =

C:C

a =

43

32

7

7

2

4

4

1

Output:

Output-1.5

Conclusion

We know that nowadays a, most of the data comes in excel format only, therefore to deal with excel files is little difficult. But by using Matlab we can easily import and export the data from excel to Matlab or Matlab to excel. We can read the excel data in various ways as per our need and as per application need. Matlab operates on excel data very effectively and efficiently.

Recommended Articles

This is a guide to xlsread Matlab. Here we also discuss the introduction and how does xlsread work in matlab? along with different examples and its code implementation. you may also have a look at the following articles to learn more –

  1. xlabel Matlab
  2. Matlab mesh()
  3. Plot Vector Matlab
  4. Size Function in MATLAB

Introduction

In the previous tutorial, we learnt how to write to an Excel file from Matlab. This tutorial is a follow-up article on how to read from an Excel file from Matlab.
In this tutorial, we will learn how to read the data from an Excel file and use the data in Matlab. At the end of this tutorial, you will learn how to open an Microsoft Excel file,
read  data from a particular column into Matlab and save it in the workspace. Finally, we will plot the data and insert this plot into the same excel file.

Steps

Step 1 : The first step is to create a COM server which runs the Excel Application.

Excel = actxserver('Excel.Application'); 

This assumes that the Excel Application is installed in your system. If Excel is not installed, this statement will give an error. You can put the above statement within a try-catch block:

try
    Excel = actxserver('Excel.Application');
catch
    Excel = [];    
end 

Step 2: In this step, we will check the version of Excel.

ExcelVersion = str2num(Excel.Version);   

If the Microsoft Excel is 2007, 2010 or above, you would get ExcelVersion would be 12 or above. In such a case, you can handle all the Excel workbook files
with extensions *.xls, *.xlsx and *.xlsm. If the version is less than 12, only *.xls file would be supported. 

Step 3: In this step, we will open an Excel file “ResultFile.xls” in the current directory.

ResultFile = [pwd 'ResultFile.xls']; 
Workbook = invoke(Excel.Workbooks,'Open', ResultFile);   

Step 4: By default, the visibility of the Excel file is set to
FALSE. You can make the Excel file visible using the command:

set(Excel,'Visible',1);

Let us assume, that the Excel file looks something like this as shown in the figure. Let us develop the code to read the data from Column A and Column B in to 2 variables
iter and expResults. We will plot this data and insert this plot into the same excel file.

ResultFile = [pwd 'ResultFile.xls'];
Workbook = invoke(Excel.Workbooks,'Open', ResultFile);
resultsheet = 'ExperimentSheet';
try
    sheet = get(Excel.Worksheets,'Item', resultsheet);
    invoke(sheet, 'Activate');
catch
    % If the Excel Sheet ‘ExperimentSheet’ is not found, throw an error message
    errordlg([resultsheet 'not found']);
end

Read Experiment Column

As seen from the Excel sheet, we need to first read Column A from row 2 to row 11. First we need to select the range from A2 till A11. We use the
xlcolumn() function to convert between column
name and number for Excel representation. The xlcolumn() module can be downloaded from
here.

%% Read the Experiment Column
Location = [xlcolumn(1) '2:' xlcolumn(1) int2str(11)];
ExpIteration = get(Excel.Activesheet, 'Range',Location);
ExpIteration.Select;
if(iscell(Excel.Selection.Value))
    iter = cell2mat(Excel.Selection.Value)';
else
    iter = Excel.Selection.Value;
end
% The iter variable will now contain the data from the column A.  

Read Result Column

As seen from the Excel sheet, we need to first read Column B from row 2 to row 11. Here again, we need to select the range from B2 till B11.

%% Read the Results Column
Location = [xlcolumn(2) '2:' xlcolumn(2) int2str(11)];
ResultValue  = get(Excel.Activesheet, 'Range',Location);
ResultValue.Select;
if(iscell(Excel.Selection.Value))
    expResults = cell2mat(Excel.Selection.Value)';
else
    expResults = Excel.Selection.Value;
end
% The expResults variable will now contain the data from the column A. 

Plot the Data

Since we already have the data in the workspace, we can simply use the plot command in Matlab.

%% Plot the Data
plot(iter, expResults);
legend('Results');
xlabel('Experiment'); 
ylabel('Results');

Insert the image into Excel Sheet

In order to insert the plot into an excel sheet, we need to convert the figure object into an image.

% Convert the figure object to an image
ResultImage = 'Results.png';
print('-dpng', ResultImage); 

To place the image in the Excel sheet, we look for coordinates of the particular cell which is empty and place the image in that cell.
Let’s say, we will place the image starting from column D.

Location = [ xlcolumn(4)  int2str(2) ];
ImageRange= get(Excel.ActiveSheet,'Range',  Location);
Shapes =ExAct.Shapes;
%% Size of theimage.
imgWidth=400;
imgHeight=250;
Shapes.AddPicture([pwd'' ResultImage] ,0,1, ImageRange.Left, ImageRange.Top, imgWidth, imgHeight);   

The last step is to save the Excel file and close the Excel application:  

%Save and Close the Excel File
delete(Excel); 
invoke(Excel,'Quit');
invoke(Workbook,'Save'); 

Download Download ReadData.zip

ячейки ввода, определяются в строках Width и Height и раскрывающемся списке Units.

Ячейки вывода с окончательными результатами преобразовываются в текст выбором пункта Undefine Cells меню Notebook. Пользователь может переопределить стили шаблона m-book.dot так же, как и любого другого стиля, выбрав в меню Формат пункт Стили и форматирование и произведя нужные установки в появившемся диалоговом окне.

Квадратные скобки, ограничивающие ячейки и группы ячеек, пропадают при выборе пункта Hide Cell Markers меню Notebook. Пункт Show Cell Markers служит для отображения скобок в документе. При печати М- книги скобки не выводятся.

Чтение рабочего листа Excel в числовую матрицу Matlab

Создадим файл Excel с именем myExample.xlsx в рабочем каталоге Matlab. Для этого в окне Matlab выполним следующие команды

Лист с именем Лист1 в файле myExample.xlsx содержит следующие данные:

Прочтем числовые данные с первого рабочего листа Excel.

11

Чтение диапазона ячеек

Прочтем заданный диапазон ячеек из файла Excel определенного в предыдущем примере.

Чтение столбца

Прочтем второй столбец из файла Excel из первого примера.

Для получения лучшего результата рекомендуется в задаваемый диапазон включать номера строк, например, ‘B2:B4’.

Получение числовых, текстовых и необработанных данных

Примерполучениячисловых,текстовыхинеобработанных(комбинированных) данных из файла Excel, созданного в первом примере.

12

Вычисление функции на рабочем листе Excel

В Редакторе Matlab (Editor – New – Function) создадим функцию, оперирующую с данными, расположенными на рабочем листе Excel. Значениям, выходящим за пределы диапазона [0.2,0.8] будем присваивать значения 0.2 или 0.8. Функцию сохраним в файле SetMinMax.m в рабочем каталоге.

13

В Command Window добавим случайные данные к файлу myExample.xlsx.

Порезультатамвыполненияэтихкомандпоявляетсяинформационное предупреждение о том, что к заданному файлу произошло добавление нового рабочего листа и в этот лист занесены определенные нами данные.

Рабочий лист с именем MyData содержит величины в диапазоне от 0

до 1.

14

Often, we would like to process data in MATLAB that comes from an external source and which is supplied in either .csv or .xls/.xlsx format. MATLABs importdata, csvread and xlsread commands allow us to easily read and process data files.

Reading .csv files with importdata or csvread

The importdata command has the following syntax.

importdata(file, delimiter, skiprows) loads data from file where the data columns are separated with the delimiter char and numeric data starts at line skiprows+1.

A quick look at the INDPRO.csv file reveals that the numeric data starts in line 2 and columns are separated by commas (,).

Inspecting the INDPRO.csv file

Therefore, we can use the following command to read the industrial production series.

mydata = importdata(‘./INDPRO.csv’, ‘,’, 1);

The command creates a struct object called mydata which contains two sub-objects, a matrix called data containing all numerical data from the file (in this case the values of the series) and a cell-array called textdata which contains the string from the file (here header names and dates). We can explore these objects in the workspace browser or by accessing them directly.

mydata.data(1:10) % get first 10 rows of INDPRO series

mydata.textdata(1,:) % look at header names of the data

Alternatively we can also read in only the numeric data, by using the csvread command. csvread has the following syntax.

csvread(file, rowindex, columnindex) reads numeric data from file starting in row rowindex and column colindex where 0 is the first row/column.

If we only want to read the values of the INDPRO series (which starts in the second row and second column), we can use the following command.

indpro = csvread(‘./INDPRO.csv’, 1, 1)

Reading .xls/.xlsx files with xlsread

Reading excel files works best on Windows. If you are using macOS it is best practice to use .csv files if they are available or to open the .xls file in excel and to export it in a .csv format. Files in a .xlsx format usually tend to work.

xlsread has the following syntax.

xlsread(file, sheetname, excelrange) reads data from file and worksheet sheet where the data is in the block excelrange (which is supplied in the typical excel format e.g. B2:F18).

In order to read the UNRATE series, we can use the following command.

unrate = xlsread(‘./UNRATE.xls’, ‘FRED Graph’, ‘B12:B858’)

Alternatively, we can read both the numerical data along with all the text in the worksheet. We do this by specifying two outputs from xlsread.

[unrate, urtext] = xlsread(‘./UNRATE.xls’, ‘FRED Graph’);

This returns the unemployment rate in the vector unrate, and a cell that contains the text data where the dates corresponding to the unemployment rate start in column 1, row 12.

Converting string dates with datetime

Often when importing time series data, dates or datetimes are supplied as strings in various formats. When using the importdata command, dates are thus treated as textdata and imported as vectors of strings. In order to work with dates to e.g. plot a series against them, we need to convert the date strings to the datetime format which MATLAB understands.

The datetime function can be used to convert an array of string dates of a specific format into an array of datetime values. The general syntax is as follows.

datetime_vector = datetime(datestring_vector, ‘InputFormat’, formatString)

formatString is a string that describes the date format of the string representation. Here are some examples of typically used date formats.

Consider the csv import example above where we have imported the INDPRO.csv file. The first column of the mydata.textdata array contains string representations of the dates of the time series starting in line 2. We can convert these dates into the datetime format in the following way.

inddates = datetime(mydata.textdata(2:end,1), ‘InputFormat’,’yyyy-MM-dd’)

These converted dates are useful e.g. when plotting the INDPRO series. Even though we will cover this more in detail in the next section, try out the following command to show a time series plot of the INDPRO series data.

We will see the following plot.

Quick plot of INDPRO series with dates

Similarly, we can make a time series plot of the unemployment rate by first converting the dates into the datetime format

urdates = datetime(urtext(12:end,1),’InputFormat’,’dd.MM.yyyy’)

Then we can plot the unemployment rate using

Quick plot of UNRATE series with dates

Exporting data as a .mat file

The easiest way to export/save data in MATLAB is to export them as MATLAB datafile (which has a .mat extension).

As you have seen before in this course, .mat files can easily be loaded using the load command.

To save data from your MATLAB workspace into a .mat file you can use the save command. It has the following syntax.

save(filename) stores all variables in the current workspace into a file called filename.mat. save(filename, variables) stores the variables whose name is in the string list variables into a file called filename.mat.

save(‘mydata’) % Exports all variables in the workspace

save(‘mydata’, ‘X’, ‘y’) % Exports variables X and y

Saving data as .mat files is the most efficient solution when you would like to export the data to use them in a different MATLAB script or to access them later again with MATLAB. The downside is that .mat files are only readable by MATLAB. If you would like to export data in a format such that they can be imported into other programs, please read the next section.

Exporting data as a .csv file

Sometimes we would like to export our data in a format such that it can be imported into other programs which are not capable of reading .mat files.

If you would like to export numeric data that can be represented in a large matrix, MATLABs csvwrite function is a good option to write your data into a .csv file. It has the following syntax.

csvwrite('filename.csv', matrix) writes matrix matrix into a comma-separated values (.csv) file that is named filename.csv.

csvwrite(‘mydata.csv’, X)

Note that .csv files which are exported this way do not contain column headers.

Exporting data as a .xls file

Alternatively, we can export our data to a .xls or .xlsx file using the xlswrite function. In general, xlswrite behaves just like csvwrite.

xlswrite(‘mydata.xls’, X)

Furthermore, we can use xlswrite to write excel file that contain column headers by first converting the output matix into a cell. As an example, lets read the data from UNRATE.xls, convert the dates to datetime, plot the time series and then save the time series to an excel file with a column for the dates and a heading for the dates and the unemployment rate.

[unrate, urtext] = xlsread(‘./UNRATE.xls’, ‘FRED Graph’);

urdates = datetime(urtext(12:end,1),’InputFormat’,’dd.MM.yyyy’)

col_label = {‘Date’, ‘UNRATE’};

celldates = cellstr(datestr(urdates));

outputmat = [col_label; celldates num2cell(unrate)];

xlswrite(‘UNRATEout.xls’, outputmat)

Понравилась статья? Поделить с друзьями:
  • Recovery tools for excel
  • Reading excel with java
  • Real time one word or two
  • Recovery toolbox для word скачать полную версию
  • Reading excel with epplus