将 XLSX 文件导入 PHP 数组
是否可以将 XLSX 文件的每一行导入到 PHP 数组中的一行?
您可以使用 PHPExcel,它可在此处找到:https://phpexcel.codeplex.com/releases/view/119187
以下是我用来读取数组或数组的内容:xls
xlsx
require_once('/path/to/PHPExcel.php');
$filename = "example.xlsx";
$type = PHPExcel_IOFactory::identify($filename);
$objReader = PHPExcel_IOFactory::createReader($type);
$objPHPExcel = $objReader->load($filename);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheets[$worksheet->getTitle()] = $worksheet->toArray();
}
print_r($worksheets);
更新 / 2022-02-13:
PhpSpreadsheet已经存在了几年,并且已经取代了PHPExcel。以下代码或多或少与上述代码相同,但进行了一些小的改进:
/**
* Create a multidimensional array of worksheets from a filename.
*
* @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
* @param bool $calculateFormulas Should formulas be calculated?
* @param bool $formatData Should formatting be applied to cell values?
*
* @return array
*/
function spreadsheet_to_array($nullValue = null, $calculateFormulas = true, $formatData = false) {
$results = [];
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
$results[$worksheet->getTitle()] = $worksheet->toArray($nullValue, $calculateFormulas, $formatData);
}
// save memory
$spreadsheet->__destruct();
$spreadsheet = NULL;
unset($spreadsheet);
return $results;
}