Apache+php(PHPExcel)+HTML5+JavaScript(jQuery)+MySQL
<p>按照Excel表格模板(<a href="javascript:void(0);">下載</a>),填寫資料。</p>
<p>上傳已編輯的文件:</p>
<p>
<a href="javascript:void(0);" id="triggerInputFile">選擇文件</a>
<input
type="file"
id="inputFile"
style="height:0;width:0"
accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
>
<span id="filepath"></span>
<a class="hide" href="javascript:void(0);" id="uploadFile">上傳</a>
</p>
$(function() { var tipFn = function(str) { $('#tip').text(str); $('#tip').fadeIn(function() { setTimeout(function() { $('#tip').fadeOut(); }, 2000); }); }; $('#triggerInputFile').click(function() { $('#inputFile').click(); }); $('#inputFile').change(function() { var fileReader = new FileReader(); var file = $(this).prop('files')[0]; if (file) { fileReader.readAsDataURL(file); } else { tipFn('請選擇文件'); return; } fileReader.onloadend = (e) = >{ console.log(e); if (file.size > 2000000) { tipFn('文件大小不得超過 2 M'); return; } // $('#filepath').text(e.target.result); var fullpath = $(this).val(); var filename = fullpath.split('\\'); $('#filepath').text(filename[filename.length - 1]); // C:\fakepath\第三部分價格表.docx $('#uploadFile').removeClass('hide'); }; }); $('#uploadFile').click(function() { var form_data = new FormData(); var file_data = $('#inputFile').prop('files')[0]; form_data.append('id', 'xls_file'); form_data.append('name', file_data.name); form_data.append('type', file_data.type); form_data.append('lastModifiedDate', file_data.lastModifiedDate); form_data.append('size', file_data.size); form_data.append('upfile', file_data); $.ajax({ type: 'POST', url: '/excel/upload', dataType: 'json', processData: false, contentType: false, cache: false, data: form_data }).success(function(json) { if (json.error === 0) { tipFn('文件上傳成功!'); $('#uploadFile').addClass('hide'); } else { tipFn('文件上傳失敗,緣由:' + json.message); } }); }); });
public function upload() { //定義容許上傳的文件擴展名 $ext_arr = array( 'excel' => array('xls', 'xlsx') ); //最大文件大小 $min_size = 1; $max_size = 2000000; if (empty($_FILES) === false) { //原文件名 $file_name = $_FILES['upfile']['name']; //服務器上臨時文件名 $tmp_name = $_FILES['upfile']['tmp_name']; //die($tmp_name); //文件大小 $file_size = $_FILES['upfile']['size']; //檢查文件名 if (!$file_name) { $this->alert('請選擇文件。'); } //判斷文件是不是經過 HTTP POST 上傳的 if (is_uploaded_file($tmp_name) === false) { $this->alert('上傳失敗。'); } //檢查文件大小 if ($file_size > $max_size) { $this->alert('上傳文件大小超過限制。'); } if ($file_size < $min_size) { $this->alert('上傳文件大小太小。'); } //得到文件擴展名 $temp_arr = explode('.', $file_name); $file_ext = array_pop($temp_arr); $file_ext = trim($file_ext); $file_ext = strtolower($file_ext); //檢查擴展名 if (in_array($file_ext, $ext_arr['excel']) === false) { $this->alert('上傳文件擴展名是不容許的擴展名。\\n只容許'. implode(',', $ext_arr['excel']) . '格式。'); } $save_path = $_SERVER['DOCUMENT_ROOT'].'/upload/'; if (!file_exists($save_path)) { mkdir($save_path, 0777, true); } $new_file_name = md5(uniqid(rand())); $new_file_name .= '.'.$file_ext; //移動文件 $file_path = $save_path.$new_file_name; if (move_uploaded_file($tmp_name, $file_path) === false) { $this->alert('上傳文件失敗。'); } else { header('Content-type: text/plain; charset=UTF-8'); $result = $this->show_excel($file_path); echo '{"error":0, "url":"/upload/'.$new_file_name.'","msg":'.$result.'}'; //刪除本地文件 // $this->del_file($file_path); } } } private function show_excel($file_path) { //Include class require_once($_SERVER['DOCUMENT_ROOT'].'/Classes/PHPExcel.php'); require_once($_SERVER['DOCUMENT_ROOT'].'/Classes/PHPExcel/Writer/Excel2007.php'); //文件的擴展名 $ext = strtolower(pathinfo($file_path, PATHINFO_EXTENSION)); // 讀excel if ($ext === 'xlsx') { // $objReader = PHPExcel_IOFactory::createReader('Excel2007'); require_once($_SERVER['DOCUMENT_ROOT'].'/Classes/PHPExcel/Reader/Excel2007.php'); $objReader = new PHPExcel_Reader_Excel2007; $objPHPExcel = $objReader->load($file_path, 'utf-8'); } elseif ($ext === 'xls') { // $objReader = PHPExcel_IOFactory::createReader('Excel5'); require_once($_SERVER['DOCUMENT_ROOT'].'/Classes/PHPExcel/Reader/Excel5.php'); $objReader = new PHPExcel_Reader_Excel5; $objPHPExcel = $objReader->load($file_path, 'utf-8'); } $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow(); // 取得總行數 $highestColumn = $sheet->getHighestColumn(); // 取得總列數 $ar = array(); $nar = array(); $i = 0; $importRows = 0; for ($j = 2; $j <= $highestRow; $j++) { $importRows++; $realName = (string)$objPHPExcel->getActiveSheet()->getCell("A$j")->getValue(); //須要導入的realName $phone = (string)$objPHPExcel->getActiveSheet()->getCell("B$j")->getValue(); //須要導入的phone $company = (string)$objPHPExcel->getActiveSheet()->getCell("C$j")->getValue(); //須要導入的company $job = (string)$objPHPExcel->getActiveSheet()->getCell("D$j")->getValue(); //須要導入的job $qq = (string)$objPHPExcel->getActiveSheet()->getCell("E$j")->getValue(); //須要導入的email $ret['mdata'] = 0; array_push($nar, $realName); // $ret['mdata'] = $this->addMemb($phone, $realName, $company, $job, $qq); //這裏就是個人數據庫添加操做定義的一個方法,對應替換爲本身的 if ($ret['mdata'] && !is_Bool($ret['mdata'])) { $ar[$i] = $ret['mdata']; $i++; } } if ($i > 0) { $ret['res'] = "0"; $ret['errNum'] = $i; $ret['allNum'] = $importRows; $ret['sucNum'] = $importRows - $i; $ret['mdata'] = $ar; $ret['msg'] = "導入完畢!"; return json_encode($ret); } $ret['res'] = "1"; $ret['allNum'] = $importRows; $ret['errNum'] = 0; $ret['sucNum'] = $importRows; $ret['mdata'] = "導入成功!"; $ret['nar'] = $nar; return json_encode($ret); } private function alert($msg='null') { header('Content-type: text/plain; charset=UTF-8'); echo '{"error":1, "message":"'.$msg.'"}'; exit; }
上傳結果:javascript
{ "error": 0, "url": "/upload/caeaba6fdf8106a3425aead0401d5c5c.xlsx", "msg": { "mdata": "導入成功!", "res": "1", "allNum": 10, "errNum": 0, "sucNum": 10, "nar": [ "但秀逸", "禹雪兒", "果智", "沙怡", "岑陽秋", "粘萌", "興飛蘭", "白翰飛", "危莞爾", "輝迎絲" ] } }
注意:php
請根據自身需求參考上面代碼,而不要直接使用上面演示代碼,這裏僅提供一個簡單的思路。html
來源:https://xushanxiang.com/2019/11/excel-uses-php-to-import-the-database.html前端