thinkphp6上传xlsx文件

文章描述:

thinkphp6上传xlsx文件,然后把xlsx文件数据导入数据库

html

<form action="" enctype="multipart/form-data" method="post">
    <input type="file" name="file" />
    <br>
    <input type="submit" value="上传" />
</form>

 

php

ini_set('memory_limit', '1024M');
if ($this->request->isPost()) {
      $file = request()->file('file');
      // 上传到本地服务器
      $extension = $file->getOriginalExtension();
      if($extension !='xlsx'){
                echo "请上传xlsx格式文件";
      }
            
      $savename = \think\facade\Filesystem::disk('public')->putFile( 'file', $file);
      //获取文件路径
      $path = '/public/storage/'.$savename;
      echo $path;
}

路径

$path = ROOT_PATH . 'storage/'.$savename;
$path = 'storage/'.$savename;

 

导入xlsx

1、PHPExcel文件下载

地址: https://github.com/PHPOffice/PHPExcel

2、/public/index.php入口文件引入

include __DIR__ . '/../extend/Classes/PHPExcel.php';
include __DIR__ . '/../extend/Classes/PHPExcel/IOFactory.php';

3、导入数据

$filename = 'E:/phpstudy_pro/WWW/10004/tp/public/storage/file/20230118\416e35a288a8159a4c281772481d36f5.xlsx';
$extension = pathinfo($filename, PATHINFO_EXTENSION);

if($extension=="xlsx"){
      $reader = \PHPExcel_IOFactory::createReader('Excel2007');
}else{
      $reader = \PHPExcel_IOFactory::createReader('Excel5');
}
$excel = $reader->load($filename,$encode = 'utf-8');

$sheet = $excel->getSheet(0)->toArray();

//读取第一张表
//获取总行数
array_shift($sheet);  //删除第一个数组(标题);
$data = [];
$i = 0;
foreach ($sheet as $k => $v) {
     if(is_numeric($v[1])){
                $v[1] = (int)$v[1];
     }
     $data[$k]['pt_name'] = $v[0];
     $data[$k]['username'] = $v[1]; // password_hash($v[1],PASSWORD_BCRYPT);
     $data[$k]['phone'] = $v[2];
     $data[$k]['state_info'] = $v[3];
     $data[$k]['zizhi'] = '';
     $data[$k]['newstime'] = time();
     $i++;
}
//   echo '<pre>';
//   print_r($data);
Db::name('service_feedback')->insertAll($data);

 

发布时间:2023/01/18

发表评论