Codeigniter(CI)结合PHPExcel类完成数据导入
1. 安装PHPExcel到Codeigniter
1) 解压压缩包里的Classes文件夹中的内容到application\libraries\目录下,目录结构如下:
– application\libraries\PHPExcel.php
– application\libraries\PHPExcel (文件夹)
2)修改application\libraries\PHPExcel\IOFactory.php 文件
– 将其类名从PHPExcel_IOFactory改为IOFactory,遵从CI类命名规则。
– 将其构造函数改为public(__construct)
2. 安装完毕,写一个导出excel的控制器(Controller)
public function index(){
//判断上传文件存在值
if(!empty($_FILES)){
$filename = $_FILES['file']['name'];//被上传文件的名称
$filetype = $_FILES["file"]["type"];//被上传文件的类型
$filesize = $_FILES["file"]["size"];// 被上传文件的大小,以字节计
$filetmp = $_FILES["file"]["tmp_name"];//存储在服务器的文件的临时副本的名称
$fileerror = $_FILES["file"]["error"];//由文件上传导致的错误代码
//判断是否上传成功
if($fileerror==0){
//判断是否是excel表格
if($filetype=="application/vnd.ms-excel" || $filetype=="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){
/*设置保存路径*/
$filePath = 'uploads/excel/';
$str = "";
/*加载PHPExcel*/
$this->load->library('PHPExcel.php');
$this->load->library('PHPExcel/IOFactory.php');
//$this->load->library('PHPExcel/Reader/Excel5.php');
//注意设置时区
$time=date("YmdHis");//去当前上传的时间
//获取上传文件的扩展名
$extend=strrchr ($filename,'.');
//上传后的文件名
$name=$time.$extend;
//上传后的文件名地址
$uploadfile=$filePath.$name;//上传后的文件名地址
//move_uploaded_file() 函数将上传的文件移动到新位置。若成功,则返回 true,否则返回 false。
$result=move_uploaded_file($filetmp,$uploadfile);//假如上传到当前目录下
//echo $result;
//如果上传文件成功,就执行导入excel操作
if($result){
$inputFileType = IOFactory::identify($uploadfile);//确定输入文件的格式
$objReader = IOFactory::createReader($inputFileType);//穿件相对应的阅读器
$objPHPExcel = $objReader->load($uploadfile); //加载要读取的文件
$sheet = $objPHPExcel->getSheet(); //得到当前活动sheet
$highestRow = $sheet->getHighestRow(); //取得总行数
$highestColumn = $sheet->getHighestColumn(); //取得总列数
// print_r($highestRow);
//print_r($highestColumn);
/* 第一种方法
//循环读取excel文件,读取一条,插入一条
for($j=1;$j {
for($k='A';$k {
//
//这种方法简单,但有不妥,以'\\'合并为数组,再分割\\为字段值插入到数据库
//实测在excel中,如果某单元格的值包含了\\导入的数据会为空
//
$str .=$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().'\\';//读取单元格
}
//echo $str; die();
//explode:函数把字符串分割为数组。
$strs = explode("\\",$str);
print_r($strs);
$sql = "INSERT INTO te(`id`, `name`) VALUES (
'{$strs[0]}',
'{$strs[1]}')";
//die($sql);
if(!mysql_query($sql))
{
return false;
echo 'sql语句有误';
}
mysql_query($sql);
$str = "";
}
unlink($uploadfile); //删除上传的excel文件
$msg = "导入成功!";
*/
/* 第二种方法*/
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数
$headtitle=array();
for ($row = 2;$row
$arr=array();
//注意highestColumnIndex的列数索引从0开始
for ($col = 0;$col
$arr[$col] =$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
}
// $sql = "INSERT INTO admins(`account`, `pwd`, `username`, `power`, `tel`,`sex`,`work_numjob`,`job`,`sector`) VALUES (
// '{$strs[0]}',
// '{$strs[1]}',
// '{$strs[2]}',
// '{$strs[3]}',
// '{$strs[4]}',
// '{$strs[5]}',
// '{$strs[6]}',
// '{$strs[7]}',
// '{$strs[8]}',)";
$data=array(
'account'=>$arr['0'],
'pwd'=>$arr['1'],
'username'=>$arr['2'],
'power'=>$arr['3'],
'tel'=>$arr['4'],
'sex'=>$arr['5'],
'work_num'=>$arr['6'],
'job'=>$arr['7'],
'sector'=>$arr['8'],
);
$this->db->insert("admins",$data);
}
unlink($uploadfile);
show_msg("导入成功",site_url("链接地址"));//跳转地址
//删除上传的excel文件
}
}else{
show_msg("上传文件非cvs格式,请重新上传");
}
}else{
switch ($fileerror){
case 1:
show_msg("上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值.");
break;
case 2:
show_msg("上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值");
break;
case 3:
show_msg("文件只有部分被上传");
break;
case 4:
show_msg("没有文件被上传");
break;
}
}
}
}
注意事项:阅读方式excel方式不能指定死,让他自动识别文件来自动读取。
3. 读取excel详细资料
1. 导入一个Excel最简单的方法是使用PHPExel的IO Factory,调用PHPExcel_IOFactory类的静态法load,它可以自动识别文档格式,包括Excel2007、 Excel2003XML、OOCalcSYLK、Gnumeric、CSV。返回一个PHPExcel的实例。
//加载工厂类
include'PHPExcel/IOFactory.php';
//要读取的xls文件路径
$inputFileName = './sampleData/example1.xls';
/** 用PHPExcel_IOFactory的load方法得到excel操作对象 **/
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
//得到当前活动表格,调用toArray方法,得到表格的二维数组
$sheetData =$objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
var_dump($sheetData);
1. 创建一个ExcelReader去加载一个Excel文档
如果你知道这个Excel文档的格式,可以建立一个相应的Reader去加载要读取的Excel文档。但是如果你加载了错误的文档类型,可会产生不可预知的错误。
$inputFileName = './sampleData/example1.xls';
/** Create a new Excel5 Reader **/
$objReader = new PHPExcel_Reader_Excel5();
// $objReader = new PHPExcel_Reader_Excel2007();
// $objReader = new PHPExcel_Reader_Excel2003XML();
// $objReader = new PHPExcel_Reader_OOCalc();
// $objReader = new PHPExcel_Reader_SYLK();
// $objReader = new PHPExcel_Reader_Gnumeric();
// $objReader = new PHPExcel_Reader_CSV();
/** Load $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
//得到当前活动sheet
$curSheet =$objPHPExcel->getActiveSheet();
//以二维数组形式返回该表格的数据
$sheetData = $curSheet->toArray(null,true,true,true);
var_dump($sheetData);
也可以用PHPExcel_IOFactory的createReader方法去得到一个Reader对象,无需知道要读取文件的格式。
$inputFileType = 'Excel5';
// $inputFileType = 'Excel2007';
// $inputFileType = 'Excel2003XML';
// $inputFileType = 'OOCalc';
// $inputFileType = 'SYLK';
// $inputFileType = 'Gnumeric';
// $inputFileType = 'CSV';
$inputFileName = './sampleData/example1.xls';
/** Create a new Reader of the type defined in $inputFileType **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Load $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
//得到当前活动sheet
$curSheet = $objPHPExcel->getActiveSheet();
//以二维数组形式返回该表格的数据
$sheetData = $curSheet->toArray(null,true,true,true);
var_dump($sheetData);
如果在读取文件之前,文件格式未知,你可以通过IOFactory 的 identify()方法得到文件类型,然后通过createReader()方法去穿件阅读器。
$inputFileName = './sampleData/example1.xls';
/** 确定输入文件的格式 **/
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
/** 穿件相对应的阅读器 **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** 加载要读取的文件 **/
$objPHPExcel = $objReader->load($inputFileName);
在使用load()方法加载文件之前,可以设置读取选项来控制load的行为.
2.1.ReadingOnly Data from a Spreadsheet File
setReadDataOnly()方法,配置阅读器不关注表格数据的数据类型,都以string格式返回
$inputFileType = 'Excel5';
$inputFileName = './sampleData/example1.xls';
/** Create a new Reader of the type defined in $inputFileType **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** 配置单元格数据都以字符串返回 **/
$objReader->setReadDataOnly(true);
/** Load $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
$sheetData =$objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
var_dump($sheetData);
详细资料:http://blog.csdn.net/andy1219111/article/details/7673796;

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
