标签:
用的是CI框架,用CI系统自带方法引入插件类,当类名和引入名不一致就会出现引入失败的问题
$this->load->library()
解决方法:include 或者 require 引入插件
①导出excel
1.引入类
require_once FCPATH . ‘plugins/PHPExcel/PHPExcel.php‘; require_once FCPATH . ‘plugins/PHPExcel/PHPExcel/Writer/Excel2007.php‘; //require_once FCPATH . ‘plugins/PHPExcel/PHPExcel/Writer/Excel5.php‘; require_once FCPATH . ‘plugins/PHPExcel/PHPExcel/IOFactory.php‘;
2.设置格式
$excel = new PHPExcel(); //设置当前的sheet $excel->setActiveSheetIndex(0); //可以有多个内联表 $active_sheet = $excel->getActiveSheet(); //设置sheet的name $active_sheet->setTitle(‘快递‘); //设置居中 $active_sheet->getStyle(‘A‘)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //设置标题加粗 $active_sheet->getStyle(‘A1‘)->getFont()->setBold(true); //设置单元格宽度 $active_sheet->getColumnDimension(‘A‘)->setWidth(10); //设置标题 $active_sheet->setCellValue(‘A1‘, ‘id‘);
3.填充内容
//数据从第二行开始 $i = 2; foreach ($orders as $order) { //设置单元格的值 $active_sheet->setCellValue(‘A‘ . $i, $order[‘id‘]); $i++; }
4.保存文件名
$save_name = ‘快递‘; $ua = $_SERVER["HTTP_USER_AGENT"]; //处理IE导出中文名称乱码 if (preg_match("/MSIE/", $ua)) { $save_name = urlencode($save_name); } //excel头参数 header(‘Content-Type: application/vnd.ms-excel‘); //日期为文件名后缀 header(‘Content-Disposition: attachment;filename="‘ . $save_name . ‘.xlsx"‘); header(‘Cache-Control: max-age=0‘); //excel5为xls格式,excel2007为xlsx格式 $objWriter = PHPExcel_IOFactory::createWriter($excel, ‘Excel2007‘); $objWriter->save(‘php://output‘);
②导入excel
1.引入类
require_once FCPATH . ‘plugins/PHPExcel/PHPExcel.php‘; require_once FCPATH . ‘plugins/PHPExcel/PHPExcel/Reader/Excel2007.php‘; //require_once FCPATH . ‘plugins/PHPExcel/PHPExcel/Reader/Excel5.php‘; require_once FCPATH . ‘plugins/PHPExcel/PHPExcel/IOFactory.php‘;
2.加载信息
$objReader = PHPExcel_IOFactory::createReader(‘Excel2007‘); $objPHPExcel = $objReader->load($excel_file_full_name); //excel路径 $sheet = $objPHPExcel->getSheet(0);//第一张表 //取得总行数 为数字 $highestRow = $sheet->getHighestRow(); //取得总列数 为大写字母 $highestColumn = $sheet->getHighestColumn();
3.提取内容
for ($j = 2; $j <= $highestRow; $j++) //从第二行开始读取数据 { $row = array(); //保存一行数据 即一条记录 for ($k = ‘A‘; $k <= $highestColumn; $k++) //从A列读取数据 { $row[] = $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue(); } //执行插入操作 $order = $this->order_model->add($row); } @unlink($excel_file_full_name); //删除文件
phpExcel 是一款功能强大的插件可以支持csv,pdf,excel 等格式导入和导出在项目中也是经常用到的实用工具
标签:
原文地址:http://www.cnblogs.com/zc123/p/5829002.html