FastExcelReader是 FastExcelPhp 專案的一部分,該專案包括
該庫被設計為輕量級、超快並且需要最少的記憶體使用。
FastExcelReader可以讀取 XLSX 格式 (Office 2007+) 的 Excel 相容電子表格。它只讀取數據,但速度非常快且記憶體使用量最少。
特徵
使用composer
將FastExcelReader安裝到您的專案中:
composer require avadim/fast-excel-reader
跳轉至:
您可以在/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 ();
你將會得到這個陣列:
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 ();
你將會得到這個陣列:
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 ();
你將會得到這個陣列:
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' => ...]
// ...
}
逐行讀取的另一種方法
// 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 );
你會得到這樣的結果:
Array
(
[2] => Array
(
['col1'] => 111
['col2'] => 'aaa'
)
[3] => Array
(
['col1'] => 222
['col2'] => 'bbb'
)
)
可選的第二個參數指定結果數組鍵
// Rows and cols start from zero
$ result = $ excel -> readRows ( false , Excel:: KEYS_ZERO_BASED );
你會得到這樣的結果:
Array
(
[0] => Array
(
[0] => 'col1'
[1] => 'col2'
)
[1] => Array
(
[0] => 111
[1] => 'aaa'
)
[2] => Array
(
[0] => 222
[1] => 'bbb'
)
)
結果模式的允許值
模式選項 | 描述 |
---|---|
KEYS_ORIGINAL | 行從“1”開始,列從“A”開始(預設) |
KEYS_ROW_ZERO_BASED | 從 0 開始的行 |
KEYS_COL_ZERO_BASED | 從 0 開始的列 |
KEYS_ZERO_BASED | 行從 0 開始,列從 0 開始(與 KEYS_ROW_ZERO_BASED + KEYS_COL_ZERO_BASED 相同) |
KEYS_ROW_ONE_BASED | 從 1 開始的行 |
KEYS_COL_ONE_BASED | 列從 1 |
KEYS_ONE_BASED | 行從 1 開始,列從 1 開始(與 KEYS_ROW_ONE_BASED + KEYS_COL_ONE_BASED 相同) |
可與結果模式結合使用的附加選項
選項 | 描述 |
---|---|
KEYS_FIRST_ROW | 與第一個參數中的true相同 |
KEYS_RELATIVE | 區域(非工作表)左上角單元格的索引 |
KEYS_SWAP | 交換行和列 |
例如
$ result = $ excel -> readRows ([ ' A ' => ' bee ' , ' B ' => ' honey ' ], Excel:: KEYS_FIRST_ROW | Excel:: KEYS_ROW_ZERO_BASED );
你會得到這樣的結果:
Array
(
[0] => Array
(
[bee] => 111
[honey] => 'aaa'
)
[1] => Array
(
[bee] => 222
[honey] => 'bbb'
)
)
預設情況下,庫已經跳過空白單元格和空白行。空白單元格是沒有寫入任何內容的儲存格,空白行是所有儲存格都是空的行。如果儲存格包含空字串,則不將其視為空。但您可以更改此行為並跳過帶有空白字串的儲存格。
$ 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
}
其他方式
$ 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 );
您可以透過工作簿中定義的名稱來設定讀取區域。例如,如果工作簿已定義名稱標題,範圍為Demo1!$B$4:$D$4 ,則您可以按此名稱讀取儲存格
$ excel -> setReadArea ( ' Values ' );
$ cells = $ excel -> readCells ();
請注意,由於該值包含工作表名稱,因此該工作表將成為預設工作表。
您可以在工作表中設定讀取區域
$ sheet = $ excel -> getSheet ( ' Demo1 ' )-> setReadArea ( ' Headers ' );
$ cells = $ sheet -> readCells ();
但是如果你嘗試在另一張紙上使用這個名稱,你會得到一個錯誤
$ sheet = $ excel -> getSheet ( ' Demo2 ' )-> setReadArea ( ' Headers ' );
// Exception: Wrong address or range "Values"
如有必要,您可以使用帶有回呼函數的readSheetCallback()
方法來完全控制讀取過程
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 );
預設情況下,所有日期時間值均傳回為時間戳記。但是您可以使用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 ;
});
有時,如果儲存格的格式指定為日期但不包含日期,則庫可能會誤解該值。為了避免這種情況,您可以停用日期格式
此處,儲存格 B1 包含字串“3.2”,儲存格 B2 包含日期 2024-02-03,但這兩個儲存格都設定為日期格式
$ 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 );
該庫嘗試確定單元格值的類型,並且在大多數情況下它做得正確。因此,您將獲得數字或字串值。預設情況下,日期值會作為時間戳記返回。但是您可以透過設定日期格式來變更此行為(請參閱 date() php 函數的格式選項)。
$ excel = Excel:: open ( $ file );
$ result = $ excel -> readCells ();
print_r ( $ result );
上面的例子將會輸出:
Array
(
[B2] => -2205187200
[B3] => 6614697600
[B4] => -6845212800
)
$ excel = Excel:: open ( $ file );
$ excel -> setDateFormat ( ' Y-m-d ' );
$ result = $ excel -> readCells ();
print_r ( $ result );
上面的例子將會輸出:
Array
(
[B2] => '1900-02-14'
[B3] => '2179-08-12'
[B4] => '1753-01-31'
)
通常讀取函數僅傳回儲存格值,但您可以使用樣式讀取值。在這種情況下,對於每個單元格,不會傳回標量值,而是傳回一個數組,如 ['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 ();
或者您只能讀取樣式(沒有值)
$ 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,
)
*/
但我們不建議對大檔案使用這些方法
XLSX 檔案中的每個工作表都可以包含一組資料驗證規則。要檢索它們,您可以暗示在工作表上呼叫getDataValidations
$ 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',
],
]
*/
檢索工作表中特定列的寬度:
$ 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
檢索工作表中特定行的高度:
$ excel = Excel:: open ( $ file );
$ sheet = $ excel -> selectSheet ( ' SheetName ' );
// Get the height of row 1
$ rowHeight = $ sheet -> getRowHeight ( 1 );
echo $ rowHeight ; // Example: 15
檢索工作表的凍結窗格資訊:
$ 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'
)
*/
檢索工作表的選項卡顏色資訊:
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'
)
*/
您可以使用以下方法:
Sheet::getMergedCells()
-- 傳回所有合併範圍Sheet::isMerged(string $cellAddress)
-- 檢查儲存格是否合併Sheet::mergedRange(string $cellAddress)
-- 傳回指定儲存格的合併範圍例如
if ( $ sheet -> isMerged ( ' B3 ' )) {
$ range = $ sheet -> mergedRange ( ' B3 ' );
}
getSheetNames()
-- 傳回所有工作表的名稱數組sheet(?string $name = null)
-- 傳回預設或指定的工作表getSheet(string $name, ?string $areaRange = null, ?bool $firstRowKeys = false)
-- 依名稱取得工作表getSheetById(int $sheetId, ?string $areaRange = null, ?bool $firstRowKeys = false)
-- 透過 id 取得工作表getFirstSheet(?string $areaRange = null, ?bool $firstRowKeys = false)
-- 取得第一張工作表selectSheet(string $name, ?string $areaRange = null, ?bool $firstRowKeys = false)
-- 依名稱選擇預設工作表並傳回它selectSheetById(int $sheetId, ?string $areaRange = null, ?bool $firstRowKeys = false)
-- 按 id 選擇預設工作表並傳回selectFirstSheet(?string $areaRange = null, ?bool $firstRowKeys = false)
-- 選擇第一個工作表作為預設值並傳回它getDefinedNames()
-- 傳回工作簿的定義名稱name()
-- 傳回字串的名稱isActive()
-- 活動工作表isHidden()
-- 如果工作表隱藏isVisible()
-- 如果工作表可見state()
-- 傳回工作表的字串狀態(在isHidden()
和isVisible()
中使用)dimension()
-- 從工作表屬性傳回預設工作區域的尺寸countRows()
-- 計算維度中的行數countColumns()
-- 計算維度中的列數firstRow()
-- 第一行號firstCol()
-- 第一列字母readFirstRow()
-- 以陣列形式傳回第一行單元格的值readFirstRowWithStyles()
-- 以陣列形式傳回第一行儲存格的值和樣式getColumnWidth(int)
-- 傳回給定列號的寬度getFreezePaneConfig()
-- 傳回包含凍結窗格配置的陣列getTabColorConfiguration()
-- 傳回包含選項卡顏色配置的陣列如果你覺得這個包有用,你可以在 GitHub 上給我一個 star。
或者你可以捐給我:)