thinkphp6导入xlsx和xls文件

文章描述:

thinkphp导入xlsx文件数据

 

安装

composer require phpoffice/phpspreadsheet

 

说明:在安装完成后,根目录的conposer.json里面可以看到

 

控制器引入

use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

 

上传导入

$file = request()->file('file');
// 获取文件后缀名
$extension = $file->getOriginalExtension();
$arr = array('xls','xlsx');
$boolvalue = in_array($extension,$arr,false);
if(!$boolvalue){
     $data['message'] = '请上传正确格式';
     return error($data);
}
$savename = \think\facade\Filesystem::disk('public')->putFile( 'file', $file);
$path = '../public/storage/'.$savename;

/* import */
$filenamex = str_replace('\\','/',$path);

if (!file_exists($filenamex)){
     echo "文件不存在";
     exit;
}
if($extension == 'xlsx'){
     $objReader = IOFactory::createReader('Xlsx');
}else{
     $objReader = IOFactory::createReader('Xls');
}

$objPHPExcel = $objReader->load($filenamex);    //  传入的文件
$sheet = $objPHPExcel->getSheet(0);   //  excel中的第一张sheet
$highestRow = $sheet->getHighestRow();          //  取得总行数
$highestColumn = $sheet->getHighestColumn();    //  取得总列数
\PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
$lines = $highestRow - 1;
if ($lines <= 0) {
      return json(['code' => 0, 'message' => '没有数据']);
}
$data = array();
for ($j = 2; $j <= $highestRow; $j++) {
     $data[$j - 2] = [
         'StaffDept'      => trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue()),
         'StaffPost'      => trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue()),
      ];
}

 

发布时间:2023/09/11

发表评论