前端上傳使用layui.upload組件,具體參考Layui手冊
php:
//主邏輯
//限制上傳表格類型
$file_type = $_FILES['excel_import']['type'];
if ($file_type!='application/vnd.ms-excel') {
return [RESULT_ERROR,'上傳失敗,只能上傳excel表格!'];
}
if (is_uploaded_file($_FILES['excel_import']['tmp_name'])) {//判斷文件上傳是否成功
$data = get_excel_data($_FILES['excel_import']['tmp_name'],2,0,'csv');
//TODO 執行導入後的邏輯
}else{
return [RESULT_ERROR, '請選擇文件後導入'];
}
//get_excel_data
/**
* 讀取excel返回數據
*/
function get_excel_data($file_url = '', $start_row = 1, $start_col = 0, $type = 'xls')
{
vendor('phpoffice/phpexcel/Classes/PHPExcel');
//此處邏輯爲解決導入xls和csv的衝突
if( $type=='xlsx'||$type=='xls' ){
$objPHPExcel = PHPExcel_IOFactory::load($file_url);
}else if( $type=='csv' ){
$objReader = PHPExcel_IOFactory::createReader('CSV')
->setDelimiter(',')
->setInputEncoding('GBK') //不設置將導致中文列內容返回boolean(false)或亂碼
->setEnclosure('"')
->setSheetIndex(0);
$objPHPExcel = $objReader->load($file_url);
}else{
die('Not supported file types!');
}
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestDataRow();
$highestColumn = $objWorksheet->getHighestDataColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$excel_data = [];
for ($row = $start_row; $row <= $highestRow; $row++)
{
for ($col = $start_col; $col < $highestColumnIndex; $col++)
{
$excel_data[$row][] =(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
}
}
return $excel_data;
}