是否可以将 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;
}
关于php - 将 XLSX 文件导入 PHP 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13439411/