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;

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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