PHPExcel是一个PHP类库,用来帮助我们简单、高效实现从Excel读取Excel的数据和导出数据到Excel。也是我们日常开发中,经常会遇到的使用场景。
导入PHPExcel
下载PHPExcel
Git下载:
https://github.com/PHPOffice/PHPExcel
百度网盘下载:https://pan.baidu.com/s/1azR7ERyACm43npmgjhvIfA 密码:jbza
引入PHPExcel
把解压下来的文件放在application/libraries
下:
代码块
Controller:
<?php
class TestImportExcel extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('TestImportExcel_model','testimportexcel_model');
}
public function importexcel(){
if ($_FILES['file']['name']) {
$tmp_file = $_FILES['file']['tmp_name'];
$file_types = explode('.', $_FILES['file']['name']);
$file_type = $file_types[count($file_types)-1];
//判断是否为excel文件
if (strtolower($file_type) != 'xlsx') {
echo "不是excel文件,请重新上传!";
}
//设置上传路径
$savePath = "./uploads/";
//文件命名
$str = date('Ymdhis');
$file_name = $str.".".$file_type;
if (!copy($tmp_file,$savePath.$file_name)) {
echo "上传失败";
}
$this->load->library('PHPExcel');
$objPHPExcel = new PHPExcel();
$objProps = $objPHPExcel->getProperties();
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($savePath . $file_name);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
//excel中的一条数据
$excel_data = array();
for ($currentRow=2; $currentRow <= $highestRow; $currentRow++) {
for ($currentColumn='A'; $currentColumn <= $highestColumn ; $currentColumn++) {
$excel_data[$currentColumn]=$objPHPExcel->getActiveSheet()->getCell($currentColumn . $currentRow)->getValue();
}
$this->testimportexcel_model->insert_excel($excel_data['A'],$excel_data['B']);
}
echo "导入成功";
}
}
}
?>
model:
<?php
class TestImportExcel_model extends CI_Model{
public function __construct(){
parent::__construct();
$this->load->database();
}
//插入数据到数据库
public function insert_excel($main_question,$answer){
$data = array(
'main_question'=>$main_question,
'answer' => $answer,
);
$this->db->insert('question_answer',$data);
}
}
?>