FastExcelReader faz parte do Projeto FastExcelPhp que consiste em
Esta biblioteca foi projetada para ser leve, super rápida e requer uso mínimo de memória.
FastExcelReader pode ler planilhas compatíveis com Excel no formato XLSX (Office 2007+). Ele apenas lê dados, mas faz isso muito rapidamente e com uso mínimo de memória.
Características
Use composer
para instalar o FastExcelReader em seu projeto:
composer require avadim/fast-excel-reader
Ir para:
Você pode encontrar mais exemplos na pasta /demo
use avadim FastExcelReader Excel ;
$ file = __DIR__ . ' /files/demo-00-simple.xlsx ' ;
// Open XLSX-file
$ excel = Excel:: open ( $ file );
// Read all values as a flat array from current sheet
$ result = $ excel -> readCells ();
Você obterá esta matriz:
Array
(
[A1] => 'col1'
[B1] => 'col2'
[A2] => 111
[B2] => 'aaa'
[A3] => 222
[B3] => 'bbb'
)
// Read all rows in two-dimensional array (ROW x COL)
$ result = $ excel -> readRows ();
Você obterá esta matriz:
Array
(
[1] => Array
(
['A'] => 'col1'
['B'] => 'col2'
)
[2] => Array
(
['A'] => 111
['B'] => 'aaa'
)
[3] => Array
(
['A'] => 222
['B'] => 'bbb'
)
)
// Read all columns in two-dimensional array (COL x ROW)
$ result = $ excel -> readColumns ();
Você obterá esta matriz:
Array
(
[A] => Array
(
[1] => 'col1'
[2] => 111
[3] => 222
)
[B] => Array
(
[1] => 'col2'
[2] => 'aaa'
[3] => 'bbb'
)
)
$ sheet = $ excel -> sheet ();
foreach ( $ sheet -> nextRow () as $ rowNum => $ rowData ) {
// $rowData is array ['A' => ..., 'B' => ...]
$ addr = ' C ' . $ rowNum ;
if ( $ sheet -> hasImage ( $ addr )) {
$ sheet -> saveImageTo ( $ addr , $ fullDirectoryPath );
}
// handling of $rowData here
// ...
}
// OR
foreach ( $ sheet -> nextRow () as $ rowNum => $ rowData ) {
// handling of $rowData here
// ...
// get image list from current row
$ imageList = $ sheet -> getImageListByRow ();
foreach ( $ imageList as $ imageInfo ) {
$ imageBlob = $ sheet -> getImageBlob ( $ imageInfo [ ' address ' ]);
}
}
// OR
foreach ( $ sheet -> nextRow ([ ' A ' => ' One ' , ' B ' => ' Two ' ], Excel:: KEYS_FIRST_ROW ) as $ rowNum => $ rowData ) {
// $rowData is array ['One' => ..., 'Two' => ...]
// ...
}
Maneira alternativa de ler linha por linha
// Init internal read generator
$ sheet -> reset ([ ' A ' => ' One ' , ' B ' => ' Two ' ], Excel:: KEYS_FIRST_ROW );
// read the first row
$ rowData = $ sheet -> readNextRow ();
var_dump ( $ rowData );
// read the next 3 rows
for ( $ i = 0 ; $ i < 3 ; $ i ++) {
$ rowData = $ sheet -> readNextRow ();
var_dump ( $ rowData );
}
// Reset internal generator and read all rows
$ sheet -> reset ([ ' A ' => ' One ' , ' B ' => ' Two ' ], Excel:: KEYS_FIRST_ROW );
$ result = [];
while ( $ rowData = $ sheet -> readNextRow ()) {
$ result [] = $ rowData ;
}
var_dump ( $ result );
// Read rows and use the first row as column keys
$ result = $ excel -> readRows ( true );
Você obterá este resultado:
Array
(
[2] => Array
(
['col1'] => 111
['col2'] => 'aaa'
)
[3] => Array
(
['col1'] => 222
['col2'] => 'bbb'
)
)
O segundo argumento opcional especifica as chaves da matriz de resultados
// Rows and cols start from zero
$ result = $ excel -> readRows ( false , Excel:: KEYS_ZERO_BASED );
Você obterá este resultado:
Array
(
[0] => Array
(
[0] => 'col1'
[1] => 'col2'
)
[1] => Array
(
[0] => 111
[1] => 'aaa'
)
[2] => Array
(
[0] => 222
[1] => 'bbb'
)
)
Valores permitidos do modo de resultado
opções de modo | descrições |
---|---|
KEYS_ORIGINAL | linhas de '1', colunas de 'A' (padrão) |
KEYS_ROW_ZERO_BASED | linhas de 0 |
KEYS_COL_ZERO_BASED | colunas de 0 |
KEYS_ZERO_BASED | linhas de 0, colunas de 0 (igual a KEYS_ROW_ZERO_BASED + KEYS_COL_ZERO_BASED) |
KEYS_ROW_ONE_BASED | linhas de 1 |
KEYS_COL_ONE_BASED | colunas de 1 |
KEYS_ONE_BASED | linhas de 1, colunas de 1 (igual a KEYS_ROW_ONE_BASED + KEYS_COL_ONE_BASED) |
Opções adicionais que podem ser combinadas com modos de resultado
opções | descrições |
---|---|
KEYS_FIRST_ROW | o mesmo que verdadeiro no primeiro argumento |
KEYS_RELATIVE | índice da célula superior esquerda da área (não da planilha) |
KEYS_SWAP | trocar linhas e colunas |
Por exemplo
$ result = $ excel -> readRows ([ ' A ' => ' bee ' , ' B ' => ' honey ' ], Excel:: KEYS_FIRST_ROW | Excel:: KEYS_ROW_ZERO_BASED );
Você obterá este resultado:
Array
(
[0] => Array
(
[bee] => 111
[honey] => 'aaa'
)
[1] => Array
(
[bee] => 222
[honey] => 'bbb'
)
)
A biblioteca já ignora células e linhas vazias por padrão. Células vazias são células onde nada está escrito e linhas vazias são linhas onde todas as células estão vazias. Se uma célula contiver uma string vazia, ela não será considerada vazia. Mas você pode alterar esse comportamento e pular células com strings vazias.
$ sheet = $ excel -> sheet ();
// Skip empty cells and empty rows
foreach ( $ sheet -> nextRow () as $ rowNum => $ rowData ) {
// handle $rowData
}
// Skip empty cells and cells with empty strings
foreach ( $ sheet -> nextRow ([], Excel:: TREAT_EMPTY_STRING_AS_EMPTY_CELL ) as $ rowNum => $ rowData ) {
// handle $rowData
}
// Skip empty cells and empty rows (rows containing only whitespace characters are also considered empty)
foreach ( $ sheet -> nextRow ([], Excel:: TRIM_STRINGS | Excel:: TREAT_EMPTY_STRING_AS_EMPTY_CELL ) as $ rowNum => $ rowData ) {
// handle $rowData
}
Outra maneira
$ sheet -> reset ([], Excel:: TRIM_STRINGS | Excel:: TREAT_EMPTY_STRING_AS_EMPTY_CELL );
$ rowData = $ sheet -> readNextRow ();
// do something
$ rowData = $ sheet -> readNextRow ();
// handle next row
// ...
use avadim FastExcelReader Excel ;
$ file = __DIR__ . ' /files/demo-02-advanced.xlsx ' ;
$ excel = Excel:: open ( $ file );
$ result = [
' sheets ' => $ excel -> getSheetNames () // get all sheet names
];
$ result [ ' #1 ' ] = $ excel
// select sheet by name
-> selectSheet ( ' Demo1 ' )
// select area with data where the first row contains column keys
-> setReadArea ( ' B4:D11 ' , true )
// set date format
-> setDateFormat ( ' Y-m-d ' )
// set key for column 'C' to 'Birthday'
-> readRows ([ ' C ' => ' Birthday ' ]);
// read other arrays with custom column keys
// and in this case we define range by columns only
$ columnKeys = [ ' B ' => ' year ' , ' C ' => ' value1 ' , ' D ' => ' value2 ' ];
$ result [ ' #2 ' ] = $ excel
-> selectSheet ( ' Demo2 ' , ' B:D ' )
-> readRows ( $ columnKeys );
$ result [ ' #3 ' ] = $ excel
-> setReadArea ( ' F5:H13 ' )
-> readRows ( $ columnKeys );
Você pode definir a área de leitura por nomes definidos na pasta de trabalho. Por exemplo, se a pasta de trabalho tiver cabeçalhos de nome definidos com intervalo Demo1!$B$4:$D$4 então você pode ler células com este nome
$ excel -> setReadArea ( ' Values ' );
$ cells = $ excel -> readCells ();
Observe que como o valor contém o nome da planilha, esta planilha se torna a planilha padrão.
Você pode definir a área de leitura na planilha
$ sheet = $ excel -> getSheet ( ' Demo1 ' )-> setReadArea ( ' Headers ' );
$ cells = $ sheet -> readCells ();
Mas se você tentar usar esse nome em outra planilha, receberá um erro
$ sheet = $ excel -> getSheet ( ' Demo2 ' )-> setReadArea ( ' Headers ' );
// Exception: Wrong address or range "Values"
Se necessário, você pode controlar totalmente o processo de leitura usando o método readSheetCallback()
com função de retorno de chamada
use avadim FastExcelReader Excel ;
$ excel = Excel:: open ( $ file );
$ result = [];
$ excel -> readCallback ( function ( $ row , $ col , $ val ) use (& $ result ) {
// Any manipulation here
$ result [ $ row ][ $ col ] = ( string ) $ val ;
// if the function returns true then data reading is interrupted
return false ;
});
var_dump ( $ result );
Por padrão, todos os valores de data e hora retornam como carimbo de data/hora. Mas você pode mudar esse comportamento usando dateFormatter()
$ excel = Excel:: open ( $ file );
$ sheet = $ excel -> sheet ()-> setReadArea ( ' B5:D7 ' );
$ cells = $ sheet -> readCells ();
echo $ cells [ ' C5 ' ]; // -2205187200
// If argument TRUE is passed, then all dates will be formatted as specified in cell styles
// IMPORTANT! The datetime format depends on the locale
$ excel -> dateFormatter ( true );
$ cells = $ sheet -> readCells ();
echo $ cells [ ' C5 ' ]; // '14.02.1900'
// You can specify date format pattern
$ excel -> dateFormatter ( ' Y-m-d ' );
$ cells = $ sheet -> readCells ();
echo $ cells [ ' C5 ' ]; // '1900-02-14'
// set date formatter function
$ excel -> dateFormatter ( fn ( $ value ) => gmdate ( ' m/d/Y ' , $ value ));
$ cells = $ sheet -> readCells ();
echo $ cells [ ' C5 ' ]; // '02/14/1900'
// returns DateTime instance
$ excel -> dateFormatter ( fn ( $ value ) => ( new DateTime ())-> setTimestamp ( $ value ));
$ cells = $ sheet -> readCells ();
echo get_class ( $ cells [ ' C5 ' ]); // 'DateTime'
// custom manipulations with datetime values
$ excel -> dateFormatter ( function ( $ value , $ format , $ styleIdx ) use ( $ excel ) {
// get Excel format of the cell, e.g. '[$-F400]h:mm:ss AM/PM'
$ excelFormat = $ excel -> getFormatPattern ( $ styleIdx );
// get format converted for use in php functions date(), gmdate(), etc
// for example the Excel pattern above would be converted to 'g:i:s A'
$ phpFormat = $ excel -> getDateFormatPattern ( $ styleIdx );
// and if you need you can get value of numFmtId for this cell
$ style = $ excel -> getCompleteStyleByIdx ( $ styleIdx , true );
$ numFmtId = $ style [ ' format-num-id ' ];
// do something and write to $result
$ result = gmdate ( $ phpFormat , $ value );
return $ result ;
});
Às vezes, se o formato de uma célula for especificado como data, mas não contiver uma data, a biblioteca poderá interpretar mal esse valor. Para evitar isso, você pode desativar a formatação de data
Aqui, a célula B1 contém a string "3.2" e a célula B2 contém a data 03/02/2024, mas ambas as células estão definidas para o formato de data
$ excel = Excel:: open ( $ file );
// default mode
$ cells = $ sheet -> readCells ();
echo $ cell [ ' B1 ' ]; // -2208798720 - the library tries to interpret the number 3.2 as a timestamp
echo $ cell [ ' B2 ' ]; // 1706918400 - timestamp of 2024-02-03
// date formatter is on
$ excel -> dateFormatter ( true );
$ cells = $ sheet -> readCells ();
echo $ cell [ ' B1 ' ]; // '03.01.1900'
echo $ cell [ ' B2 ' ]; // '3.2'
// date formatter is off
$ excel -> dateFormatter ( false );
$ cells = $ sheet -> readCells ();
echo $ cell [ ' B1 ' ]; // '3.2'
echo $ cell [ ' B2 ' ]; // 1706918400 - timestamp of 2024-02-03
// Returns count images on all sheets
$ excel -> countImages ();
// Returns count images on sheet
$ sheet -> countImages ();
// Returns image list of sheet
$ sheet -> getImageList ();
// Returns image list of specified row
$ sheet -> getImageListByRow ( $ rowNumber );
// Returns TRUE if the specified cell has an image
$ sheet -> hasImage ( $ cellAddress );
// Returns mime type of image in the specified cell (or NULL)
$ sheet -> getImageMimeType ( $ cellAddress );
// Returns inner name of image in the specified cell (or NULL)
$ sheet -> getImageName ( $ cellAddress );
// Returns an image from the cell as a blob (if exists) or NULL
$ sheet -> getImageBlob ( $ cellAddress );
// Writes an image from the cell to the specified filename
$ sheet -> saveImage ( $ cellAddress , $ fullFilenamePath );
// Writes an image from the cell to the specified directory
$ sheet -> saveImageTo ( $ cellAddress , $ fullDirectoryPath );
A biblioteca tenta determinar os tipos de valores das células e, na maioria dos casos, faz isso corretamente. Portanto, você obtém valores numéricos ou de string. Os valores de data são retornados como carimbo de data/hora por padrão. Mas você pode alterar esse comportamento definindo o formato da data (veja as opções de formatação para a função php date()).
$ excel = Excel:: open ( $ file );
$ result = $ excel -> readCells ();
print_r ( $ result );
O exemplo acima produzirá:
Array
(
[B2] => -2205187200
[B3] => 6614697600
[B4] => -6845212800
)
$ excel = Excel:: open ( $ file );
$ excel -> setDateFormat ( ' Y-m-d ' );
$ result = $ excel -> readCells ();
print_r ( $ result );
O exemplo acima produzirá:
Array
(
[B2] => '1900-02-14'
[B3] => '2179-08-12'
[B4] => '1753-01-31'
)
Normalmente, as funções de leitura retornam apenas valores de células, mas você pode ler os valores com estilos. Neste caso, para cada célula, não será retornado um valor escalar, mas uma matriz como ['v' => scalar_value , 's' => style_array , 'f' => formula ]
$ excel = Excel:: open ( $ file );
$ sheet = $ excel -> sheet ();
$ rows = $ sheet -> readRowsWithStyles ();
$ columns = $ sheet -> readColumnsWithStyles ();
$ cells = $ sheet -> readCellsWithStyles ();
$ cells = $ sheet -> readCellsWithStyles ();
Ou você pode ler apenas estilos (sem valores)
$ cells = $ sheet -> readCellStyles ();
/*
array (
'format' =>
array (
'format-num-id' => 0,
'format-pattern' => 'General',
),
'font' =>
array (
'font-size' => '10',
'font-name' => 'Arial',
'font-family' => '2',
'font-charset' => '1',
),
'fill' =>
array (
'fill-pattern' => 'solid',
'fill-color' => '#9FC63C',
),
'border' =>
array (
'border-left-style' => NULL,
'border-right-style' => NULL,
'border-top-style' => NULL,
'border-bottom-style' => NULL,
'border-diagonal-style' => NULL,
),
)
*/
$ cells = $ sheet -> readCellStyles ( true );
/*
array (
'format-num-id' => 0,
'format-pattern' => 'General',
'font-size' => '10',
'font-name' => 'Arial',
'font-family' => '2',
'font-charset' => '1',
'fill-pattern' => 'solid',
'fill-color' => '#9FC63C',
'border-left-style' => NULL,
'border-right-style' => NULL,
'border-top-style' => NULL,
'border-bottom-style' => NULL,
'border-diagonal-style' => NULL,
)
*/
Mas não recomendamos usar esses métodos com arquivos grandes
Cada planilha do seu arquivo XLSX pode conter um conjunto de regras de validação de dados. Para recuperá-los, você pode chamar getDataValidations
em sua planilha
$ excel = Excel:: open ( $ file );
$ sheet = $ excel -> sheet ();
$ validations = $ sheet -> getDataValidations ();
/*
[
[
'type' => 'list',
'sqref' => 'E2:E527',
'formula1' => '"Berlin,Cape Town,Mexico City,Moscow,Sydney,Tokyo"',
'formula2' => null,
], [
'type' => 'decimal',
'sqref' => 'G2:G527',
'formula1' => '0.0',
'formula2' => '999999.0',
],
]
*/
Recuperar a largura de uma coluna específica em uma planilha:
$ excel = Excel:: open ( $ file );
$ sheet = $ excel -> selectSheet ( ' SheetName ' );
// Get the width of column 1 (column 'A')
$ columnWidth = $ sheet -> getColumnWidth ( 1 );
echo $ columnWidth ; // Example: 11.85
Recuperar a altura de uma linha específica em uma planilha:
$ excel = Excel:: open ( $ file );
$ sheet = $ excel -> selectSheet ( ' SheetName ' );
// Get the height of row 1
$ rowHeight = $ sheet -> getRowHeight ( 1 );
echo $ rowHeight ; // Example: 15
Recupere as informações do painel congelado de uma planilha:
$ excel = Excel:: open ( $ file );
$ sheet = $ excel -> selectSheet ( ' SheetName ' );
// Get the freeze pane configuration
$ freezePaneConfig = $ sheet -> getFreezePaneInfo ();
print_r ( $ freezePaneConfig );
/*
Example Output:
Array
(
[xSplit] => 0
[ySplit] => 1
[topLeftCell] => 'A2'
)
*/
Recuperar as informações de cores da guia para uma planilha:
Copy code
$ excel = Excel:: open ( $ file );
$ sheet = $ excel -> selectSheet ( ' SheetName ' );
// Get the tab color configuration
$ tabColorConfig = $ sheet -> getTabColorInfo ();
print_r ( $ tabColorConfig );
/*
Example Output:
Array
(
[theme] => '2'
[tint] => '-0.499984740745262'
)
*/
Você pode usar os seguintes métodos:
Sheet::getMergedCells()
-- Retorna todos os intervalos mescladosSheet::isMerged(string $cellAddress)
-- Verifica se uma célula foi mescladaSheet::mergedRange(string $cellAddress)
-- Retorna o intervalo de mesclagem da célula especificadaPor exemplo
if ( $ sheet -> isMerged ( ' B3 ' )) {
$ range = $ sheet -> mergedRange ( ' B3 ' );
}
getSheetNames()
-- Retorna array de nomes de todas as planilhassheet(?string $name = null)
-- Retorna a planilha padrão ou especificadagetSheet(string $name, ?string $areaRange = null, ?bool $firstRowKeys = false)
-- Obtém planilha por nomegetSheetById(int $sheetId, ?string $areaRange = null, ?bool $firstRowKeys = false)
-- Obtém planilha por idgetFirstSheet(?string $areaRange = null, ?bool $firstRowKeys = false)
-- Obtém a primeira planilhaselectSheet(string $name, ?string $areaRange = null, ?bool $firstRowKeys = false)
-- Seleciona a planilha padrão por nome e a retornaselectSheetById(int $sheetId, ?string $areaRange = null, ?bool $firstRowKeys = false)
-- Seleciona a planilha padrão por id e a retornaselectFirstSheet(?string $areaRange = null, ?bool $firstRowKeys = false)
-- Seleciona a primeira planilha como padrão e a retornagetDefinedNames()
-- Retorna nomes definidos da pasta de trabalhoname()
-- Retorna o nome da stringisActive()
-- Planilha ativaisHidden()
-- Se a planilha estiver ocultaisVisible()
-- Se a planilha estiver visívelstate()
– Retorna o estado da string da planilha (usado em isHidden()
e isVisible()
)dimension()
-- Retorna a dimensão da área de trabalho padrão das propriedades da planilhacountRows()
-- Conta linhas da dimensãocountColumns()
-- Conta colunas da dimensãofirstRow()
-- O número da primeira linhafirstCol()
-- A letra da primeira colunareadFirstRow()
-- Retorna valores das células da 1ª linha como arrayreadFirstRowWithStyles()
-- Retorna valores e estilos de células da 1ª linha como arraygetColumnWidth(int)
– Retorna a largura de um determinado número de colunagetFreezePaneConfig()
– Retorna um array contendo a configuração do painel congeladogetTabColorConfiguration()
-- Retorna um array contendo a configuração de cores das guias se você achar este pacote útil, pode me dar uma estrela no GitHub.
Ou você pode me doar :)