上一篇我們說了導(dǎo)出Excel的方法,現(xiàn)在要來解決導(dǎo)入的問題了。
1.前臺先上傳文件,并返回上傳文件的新文件名,再點擊導(dǎo)入
<form class="well js-ajax-form" method="post" action="{:u('AdminGoods/readExcel')}">
<a class="btn btn-primary" href="javascript:upload_one('文件上傳','#excel','file','','taoke');">上傳Excel</a><input name="filename" type="text" id="excel" />
<button class="btn btn-primary js-ajax-submit" type="submit">導(dǎo)入數(shù)據(jù)</button>
</form>
2.AdminbaseController
/**
* 導(dǎo)入Excel
* @param type $Excel_file
* @return type
/
public function importExcel($Excel_file){
error_reporting(E_ALL);
date_default_timezone_set('Asia/ShangHai');
vendor("PHPExcel.PHPExcel");
/* PHPExcel_IOFactory /
// Check prerequisites
if (!file_exists($Excel_file)) {
exit("not found ".$Excel_file."\n");
}
/
重要代碼 解決Thinkphp M、D方法不能調(diào)用的問題
如果在thinkphp中遇到M 、D方法失效時就加入下面一句代碼
*/
//spl_autoload_register ( array ('Think', 'autoload' ) );
$reader = \PHPExcel_IOFactory::createReader('Excel5'); //設(shè)置以Excel5格式(Excel97-2003工作簿)
$PHPExcel = $reader->load($Excel_file); // 載入excel文件
$sheet = $PHPExcel->getSheet(0); // 讀取第一個工作表
$highestRow = $sheet->getHighestRow(); // 取得總行數(shù)
$highestColumm = $sheet->getHighestColumn(); // 取得總列數(shù)
/** 循環(huán)讀取每個單元格的數(shù)據(jù) */
for ($row = 2; $row <= $highestRow; $row++){//行數(shù)是以第1行開始
for ($column = 'A'; $column <= $highestColumm; $column++) {//列數(shù)是以A列開始
$dataset[$row][] = $sheet->getCell($column.$row)->getValue(); //讀取到數(shù)組中
// echo $column.$row.":".$sheet->getCell($column.$row)->getValue()."<br />";
}
}
return $dataset; //返回數(shù)組二維數(shù)組
exit;
}
3.AdminGoodsControoler
/**
* 讀取Excel
*/
public function readExcel() {
$save_path = "./data/upload/";
if (IS_POST) {
$file = I("post.filename");
$file || $this->error("請上傳Excel文件!");
$data = $this->importExcel($save_path.$file); //獲取數(shù)組
foreach($data as $str_arr){
$push = array(
'good_name'=>$str_arr[0],
'good_img'=>$str_arr[1],
'old_price'=>$str_arr[2],
'price'=>$str_arr[3],
'shop_url'=>$str_arr[4],
'ticket_url'=>$str_arr[7],
'start_time'=>$str_arr[5],
'stop_time'=>$str_arr[6],
'read_num'=>0,
'sale_num'=>1,
'status'=>1,
'create_time'=>time(),
'update_time'=>time(),
);
$res = $this->model->add($push);
}
if ($res) {
$this->success("導(dǎo)入成功!");
} else {
$this->error("導(dǎo)入失敗!");
}
}
}
4.簡潔完整的介紹完了excel導(dǎo)入的功能,喜歡的朋友可以作為參考和學(xué)習(xí)哦