实例:Codeigniter(CI)结合PHPExcel类完成数据导入导出

1、把下载回来的PHPExcel解压好后 放到application/libraries/下面   (PHPExcel下载地址

 


2、在你的Controller层里面引用类库

$this->load->helper ( array ('form', 'url', 'common' ) );
$this->load->library ( array( 'form_validation' ,'PHPExcel','PHPExcel/IOFactory'));

为了迎合CI 需要把phpexcel/IOFactory.php 的类名改为IOFactory 构造函数改成public


3、导入Excel

当然你要准备一个标准的Excel模板用来导入(自己定制吧)

下面贴我的代码[实际项目还导入了图片 在此省略 只显示核心代码]

function import($shop_id){
date_default_timezone_set ( 'Asia/Shanghai' ); // 解决时差

if ($this->form_validation->run () != FALSE) {

////一些可能需要的参数

$seller_id=intval($shop_id);//卖方ID

$dateline=time();//导入的时间
//////上传Excel
$config ['upload_path'] = './public/temp/';
$config ['allowed_types'] = 'xls|xlsx|xl';
$config ['max_size'] = '2000';
$config ['file_name'] = date ( 'Ymdhis', time () );
$this->load->library ( 'upload', $config );

if (! $this->upload->do_upload ()) {
$error = array ('error' => $this->upload->display_errors () );
echo $error ['error'];
echo '

返回

';
exit ();
} else {
$data = array ('upload_data' => $this->upload->data () );
$file_name = $data ['upload_data'] ['file_name'];
}


/////////////////////////读取excel
$uploadfile='./public/temp/'.$file_name;//获取上传成功的Excel
$objReader =IOFactory::createReader('Excel5');//use excel2007 for 2007 format
$objPHPExcel = $objReader->load($uploadfile);//加载目标Excel
$sheet = $objPHPExcel->getSheet(0);//读取第一个sheet
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
$succ_result=$error_result=0;//设置导入成功和失败的总数为0

/////////////////////////数据库操作
$conn = mysql_connect("10.0.4.33", "root", "xxx")  or die("Could not connect : " . mysql_error());
mysql_select_db("000") or die("Could not select database");
mysql_query("set names utf8");
//入库
for($j=2;$j<=$highestRow;$j++)
{
$strExcel='';
for($k='A';$k<= $highestColumn;$k++)
{
//读取单元格
$strExcel .= $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().',';
}
$strs=explode(",",$strExcel);

//Excel前两列必填 (这是我自己设定的Excel导入模板 产品名称、价格是不能为空的 否则跳过)
if(!empty($strs[0])&&!empty($strs[1])){
$sql="insert into b2b_goods(goods_name,goods_price,seller_id,dateline) values ('$strs[0]','$strs[1]','$strs[2]',$seller_id,'$dateline')";
mysql_query("set names utf8");
$result=mysql_query($sql) or die("execute error");
$insert_num=mysql_affected_rows();
}
else{
$error_result+=1;
continue;
}
if($insert_num>0){
$succ_result+=1;
}else{
$error_result+=1;
}
}

//弹出导入成功/失败条数的提示
$data['message']="插入成功".$succ_result."条数据!!!  插入失败".$error_result."条数据!!! ";
mysql_close($conn);
unlink('./public/temp/'.$file_name);//删除临时Excel
}else{
$data['randid']=$this->_getRandOnlyId();
}

$this->load->view ( 'shop/import_view', $data );

}

至此导入完成 。


至于导出 相对简单 看他们提供的例子。

有疑问,请留言


分享至
2013-09-10 发布 ┊ 17772 人浏览 ┊ 0 人评论 ┊ 来源:原创 ┊ 收藏
返回顶部