ThinkPHP 是一个流行的 PHP 开发框架,它提供了丰富的功能和组件,简化了 Web 应用的开发过程。读取 Excel 文件是常见的数据处理需求之一,ThinkPHP 提供了多种方式来实现这一功能。
<?php
namespace app\index\controller;
use think\Controller;
use PhpOffice\PhpSpreadsheet\IOFactory;
class Index extends Controller
{
public function readExcel()
{
$file = './excels/example.xlsx'; // Excel 文件路径
$spreadsheet = IOFactory::load($file);
$worksheet = $spreadsheet->getActiveSheet();
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // 遍历所有单元格
foreach ($cellIterator as $cell) {
echo $cell->getValue() . "\t";
}
echo "\n";
}
}
}
原因:可能是文件编码问题或者读取方式不正确。
解决方法:
IOFactory::load
方法时,可以指定编码格式:$spreadsheet = IOFactory::load($file, 'Xlsx');
原因:大文件读取会消耗大量内存和 CPU 资源。
解决方法:
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
$reader = new Xlsx();
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($file);
foreach ($spreadsheet->getActiveSheet()->getRowIterator() as $row) {
// 处理每一行数据
}
通过使用 ThinkPHP 和 PhpSpreadsheet 库,可以方便地读取和处理 Excel 文件。在实际应用中,需要注意文件编码和性能问题,采取相应的优化措施。
领取专属 10元无门槛券
手把手带您无忧上云