ThinkPHP 是一个流行的 PHP 开发框架,它提供了快速开发 Web 应用的功能。PHPExcel 是一个用于读取和写入 Excel 文件的 PHP 库。结合使用 ThinkPHP 和 PHPExcel,可以方便地在 Web 应用中实现 Excel 文件的导入和导出功能。
以下是一个简单的示例,展示如何在 ThinkPHP 中使用 PHPExcel 读取 Excel 文件:
<?php
namespace app\index\controller;
use think\Controller;
use PHPExcel;
use PHPExcel_IOFactory;
class Index extends Controller
{
public function importExcel()
{
$file = request()->file('excel');
if ($file) {
$info = $file->validate(['ext' => 'xlsx,xls'])->move(ROOT_PATH . 'public' . DS . 'uploads');
if ($info) {
$filePath = ROOT_PATH . 'public' . DS . 'uploads' . DS . $info->getSaveName();
$objPHPExcel = PHPExcel_IOFactory::load($filePath);
$sheet = $objPHPExcel->getSheet(0); // 获取第一个工作表
$highestRow = $sheet->getHighestRow(); // 获取总行数
$highestColumn = $sheet->getHighestColumn(); // 获取总列数
for ($row = 1; $row <= $highestRow; $row++) {
for ($column = 'A'; $column <= $highestColumn; $column++) {
$cellValue = $sheet->getCell($column . $row)->getValue();
// 处理单元格数据,例如存入数据库
echo $cellValue . "\t";
}
echo "\n";
}
} else {
return $this->error('上传失败');
}
} else {
return $this->error('请选择文件');
}
}
}php.ini 中的 upload_max_filesize 和 post_max_size 设置。通过以上步骤和示例代码,您可以在 ThinkPHP 中成功实现 Excel 文件的导入功能。如果遇到具体问题,可以根据错误信息进行排查和解决。