thinkphp5做excel表匯入匯出
阿新 • • 發佈:2018-12-10
public function excel(){
if (request()->isPost()) {
Loader::import('PHPExcel.PHPExcel');
Loader::import('PHPExcel.PHPExcel.PHPExcel_IOFactory');
Loader::import('PHPExcel.PHPExcel.PHPExcel_Cell');
//例項化PHPExcel
$objPHPExcel = new PHPExcel();
$file = request()->file('excel');
if ($file) {
$file_types = explode(".", $_FILES ['excel'] ['name']); // ["name"] => string(25) "excel檔名.xls"
$file_type = $file_types [count($file_types) - 1];//xls字尾
dump($file_type);
die;
$file_name = $file_types [count($file_types) - 2];//xls去後綴的檔名
/*判別是不是.xls檔案,判別是不是excel檔案*/
if (strtolower($file_type) != "xls" && strtolower($file_type) != "xlsx") {
echo '不是Excel檔案,重新上傳';
die;
}
$info = $file ->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'excel');//上傳位置
$path = ROOT_PATH . 'public' . DS . 'excel' . DS;
$file_path = $path . $info->getSaveName();//上傳後的EXCEL路徑
//獲取上傳的excel表格的資料,形成陣列
$re = $this->actionRead($file_path, 'utf-8');
array_splice($re, 1, 0);
unset($re[0]);
/*將陣列的鍵改為自定義名稱*/
$keys = array('id', 'username', 'nickname', 'password', 'salt', 'avatar', 'email', 'loginfailure', 'logintime', 'createtime', 'updatetime','token','status');
foreach ($re as $i => $vals) {
$re[$i] = array_combine($keys, $vals);
}
//遍歷陣列寫入資料庫
for ($i = 1; $i < count($re); $i++) {
$data = $re[$i];
$res = db('admin')->insert($data);
}
}
}
}
public function actionRead($filename, $encode = 'utf-8')
{
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($filename);
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$excelData = array();
for($row = 1; $row <= $highestRow; $row++)
{
for ($col = 0; $col < $highestColumnIndex; $col++)
{
$excelData[$row][]=(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
}
}
return $excelData;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="{:url('admin/index/excel')}" enctype="multipart/form-data" method="post">
<input type="file" name="excel" /> <br>
<input type="submit" value="上傳" />
</form>
</body>
</html>