Read from excel to 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)

Main Content

Spreadsheets often contain a mix of numeric and text data as well as variable and row
names, which is best represented in MATLAB® as a table. You can import data into a table using the Import
Tool
or the readtable function.

Import Spreadsheet Data Using the Import Tool

The Import Tool allows you to import into a table or other data type.
For example, read data from the sample spreadsheet file
patients.xls as a table in MATLAB. Open the file using the Import Tool and select options
such as the range of data and the output type. Then, click the Import
Selection
button to import the data into the MATLAB workspace.

Import tool showing options to specify range of data, variable names row, and output type

Import Spreadsheet Data Using readtable

Alternatively, you can read spreadsheet data into a table using the
readtable function with the file name, for
example:

T = readtable('patients.xls');

You can also select the range of data to import by specifying the range parameter.
For example, read the first five rows and columns of the spreadsheet. Specify the
range in Excel notation as
'A1:E5'.

T = readtable('patients.xls','Range','A1:E5')
T =

  4×5 table

      LastName        Gender      Age              Location               Height
    ____________    __________    ___    _____________________________    ______

    {'Smith'   }    {'Male'  }    38     {'County General Hospital'  }      71  
    {'Johnson' }    {'Male'  }    43     {'VA Hospital'              }      69  
    {'Williams'}    {'Female'}    38     {'St. Mary's Medical Center'}      64  
    {'Jones'   }    {'Female'}    40     {'VA Hospital'              }      67  

Import Spreadsheet Data as Other Data Types

In addition to tables, you can import your spreadsheet data into the MATLAB workspace as a timetable, a numeric matrix, a cell array, or separate
column vectors. Based on the data type you need, use one of these
functions.

See Also

Import Tool | readtable

Related Topics

  • Read Spreadsheet Data Using Import Tool
  • Read Spreadsheet Data into Table
  • Access Data in Tables

  • Trial Software
  • Trial Software
  • Product Updates
  • Product Updates

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

(Не рекомендуемый)
файл электронной таблицы 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

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

Понравилась статья? Поделить с друзьями:
  • Read from excel epplus
  • Read file from excel in java
  • Read faster one word at a time
  • Read fast one word at a time
  • Read excel with epplus