使用phpoffice/phpspreadsheet,導入、導出數據


安裝
composer require phpoffice/phpspreadsheet

//use \PhpOffice\PhpSpreadsheet\Spreadsheet;
//use \PhpOffice\PhpSpreadsheet\IOFactory;
//use \PHPExcel_Style_NumberFormat; //設置列的格式==>>設置文本格式
//導入數據
public function export()
{

//上傳excel文件
$file = request()->file('myfile');

  //獲取表格的大小,限制上傳表格的大小5M
    $file_size = $_FILES['myfile']['size'];
    if ($file_size > 50 * 1024 * 1024) {
       $this->error('文件大小不能超過5M');
        exit();
    }

   //限制上傳表格類型
   $fileExtendName = substr(strrchr($_FILES['myfile']["name"], '.'), 1);
   //application/vnd.ms-excel  為xls文件類型
   if ($fileExtendName != 'xls') {
       $this->error('必須為excel表格,且必須為xls格式!');
       exit();
   }
    header("content-type:text/html;charset=utf-8");

//將文件保存到public/uploads目錄下面
$info = $file->validate(['size' => 5 * 1024 * 1024, 'ext' => 'xls,xlsx'])->move('uploads');
if ($info) {
//獲取上傳到后台的文件名
$fileName = $info->getSaveName();
//獲取文件路徑
$filePath = '/www/wwwroot/obd-api/'. 'public' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $fileName;

} else {
return json(['status' => '1', 'message' => '文件過大或格式不正確導致上傳失敗-_-!']);
}

require dirname(dirname(dirname(__DIR__))).'/vendor/autoload.php';

$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
$reader->setReadDataOnly(TRUE);
$spreadsheet = $reader->load($filePath); //載入excel表格

$worksheet = $spreadsheet->getActiveSheet();
$highestRow = $worksheet->getHighestRow(); // 總行數
$highestColumn = $worksheet->getHighestColumn(); // 總列數
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); // e.g. 5

$lines = $highestRow - 2;
if ($lines <= 0) {
exit('Excel表格中沒有數據');
}

for ($row = 3; $row <= $highestRow; ++$row) {

$temp = array(
'code' => $worksheet->getCellByColumnAndRow('1', $row)->getValue(),
'name' => $worksheet->getCellByColumnAndRow('2', $row)->getValue(),
'class' => $worksheet->getCellByColumnAndRow('3', $row)->getValue(),
'describe' => $worksheet->getCellByColumnAndRow('4', $row)->getValue(),
'symptom' => $worksheet->getCellByColumnAndRow('5', $row)->getValue(),
'cause' => $worksheet->getCellByColumnAndRow('6', $row)->getValue(),
'scheme' => $worksheet->getCellByColumnAndRow('7', $row)->getValue(),
);

$list[] = $temp;
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM