您的位置:首页 > 编程语言 > PHP开发

Thinkphp中使用PHPExcel 导入导出excel

2017-12-06 11:18 651 查看
ThinkPHP版本:3.2.3

PHPExcel版本:1.8

PHPExcel 官方下载地址:https://github.com/PHPOffice/PHPExcel

下载解压后目录结构如下:



1、将目录中的 Classes 文件夹改名为 PHPExcel,

2、改名后的文件夹 复制到 Thinkphp/Library/Vender/ 目录下

完成后目录结构如下:



3、Application/Admin/Common/function.php 内添加导入导出excel的函数,代码如下:

/**
* Export Excel | 2017.12.06
* Author:武当山道士 <912900700@qq.com>
* PHPExcel Version: 1.8
+----------------------------------------------------------
* @param {string} $expTitle     导出后的文件名前缀
* @param {string} $expCellName  标题栏
* @param {array}  $expTableData 内容数组
*/
function export_excel($expTitle,$expCellName,$expTableData){
$xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
$fileName = $expTitle.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
$cellNum = count($expCellName);
$dataNum = count($expTableData);
vendor("PHPExcel.PHPExcel");
$objPHPExcel = new PHPExcel();
$cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

$objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));
for($i=0;$i<$cellNum;$i++){
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
}
// Miscellaneous glyphs, UTF-8
for($i=0;$i<$dataNum;$i++){
for($j=0;$j<$cellNum;$j++){
$objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
}
}

ob_end_clean();//清除缓存,避免中文乱码 *************** 这一行非常重要 ******************************

header('pragma:public');
header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
}

/**
* Import Excel | 2017.12.06
* Author:武当山道士 <912900700@qq.com>
* PHPExcel Version: 1.8
+----------------------------------------------------------
* @param  {file}   $file  文件流
+----------------------------------------------------------
* @return {array}  $array 返回数组
+----------------------------------------------------------
*/
function import_excel($file){
if(!file_exists($file)){
return array("error"=>0,'message'=>'file not found!');
}
Vendor("PHPExcel.PHPExcel.IOFactory");
$objReader = PHPExcel_IOFactory::createReader('Excel5');
try{
$PHPReader = $objReader->load($file);
}catch(Exception $e){}
if(!isset($PHPReader)) return array("error"=>0,'message'=>'read error!');
$allWorksheets = $PHPReader->getAllSheets();
$i = 0;
foreach($allWorksheets as $objWorksheet){
$sheetname=$objWorksheet->getTitle();
$allRow = $objWorksheet->getHighestRow();//how many rows
$highestColumn = $objWorksheet->getHighestColumn();//how many columns
$allColumn = PHPExcel_Cell::columnIndexFromString($highestColumn);
$array[$i]["Title"] = $sheetname;
$array[$i]["Cols"] = $allColumn;
$array[$i]["Rows"] = $allRow;
$arr = array();
$isMergeCell = array();
foreach ($objWorksheet->getMergeCells() as $cells) {//merge cells
foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) {
$isMergeCell[$cellReference] = true;
}
}
for($currentRow = 1 ;$currentRow<=$allRow;$currentRow++){
$row = array();
for($currentColumn=0;$currentColumn<$allColumn;$currentColumn++){;
$cell =$objWorksheet->getCellByColumnAndRow($currentColumn, $currentRow);
$afCol = PHPExcel_Cell::stringFromColumnIndex($currentColumn+1);
$bfCol = PHPExcel_Cell::stringFromColumnIndex($currentColumn-1);
$col = PHPExcel_Cell::stringFromColumnIndex($currentColumn);
$address = $col.$currentRow;
$value = $objWorksheet->getCell($address)->getValue();
if(substr($value,0,1)=='='){
return array("error"=>0,'message'=>'can not use the formula!');
exit;
}
if($cell->getDataType()==PHPExcel_Cell_DataType::TYPE_NUMERIC){
$cellstyleformat=$cell->getParent()->getStyle( $cell->getCoordinate() )->getNumberFormat();
$formatcode=$cellstyleformat->getFormatCode();
if (preg_match('/^([$[A-Z]*-[0-9A-F]*])*[hmsdy]/i', $formatcode)) {
$value=gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($value));
}else{
$value=PHPExcel_Style_NumberFormat::toFormattedString($value,$formatcode);
}
}
if($isMergeCell[$col.$currentRow]&&$isMergeCell[$afCol.$currentRow]&&!empty($value)){
$temp = $value;
}elseif($isMergeCell[$col.$currentRow]&&$isMergeCell[$col.($currentRow-1)]&&empty($value)){
$value=$arr[$currentRow-1][$currentColumn];
}elseif($isMergeCell[$col.$currentRow]&&$isMergeCell[$bfCol.$currentRow]&&empty($value)){
$value=$temp;
}
$row[$currentColumn] = $value;
}
$arr[$currentRow] = $row;
}
$array[$i]["Content"] = $arr;
$i++;
}
spl_autoload_register(array('Think','autoload'));//must, resolve ThinkPHP and PHPExcel conflicts
unset($objWorksheet);
unset($PHPReader);
unset($PHPExcel);
unlink($file);
return array("error"=>1,"data"=>$array);
}


注意:ob_end_clean();//清除缓存,避免中文乱码, 这一行非常重要 ,要放在所有header()前面

4、使用:查询mysql数据库并导出excel

后台代码:Application/Admin/Controller/MemberController.Class.php

public function expt(){

$title  = "Member";
$th  = array(
array('id','用户id'),
array('truename','姓名'),
array('phone','手机号')
);
$data  = M('Member')->Field('id,truename,phone')->select();
export_excel($title,$th,$data);
}


4.2、导入excel

public function impt(){
if(isset($_FILES["import"]) && ($_FILES["import"]["error"] == 0)){
$result = import_execl($_FILES["import"]["tmp_name"]);
if($result["error"] == 1){
$execl_data = $result["data"][0]["Content"];
foreach($execl_data as $k=>$v){
#循环写入数据库,或者开启事务..
}
}
}
}


前台代码: Application/Admin/View/Index/member.html

<a href="{:U('Admin/expt')}">导出Excell</a>
<br />
<form action="" name="impt" id="impt" method="post" enctype="multipart/form-data">
<h3>导入Excel:</h3><input  type="file" name="import" />
<input type="submit"  value="导入" onclick="impt();"/>
</form>

<!-- other code -->

<script type="text/javascript">
function impt(){
document.getElementById('impt').action="__APP__/Admin/Member/impt";
document.getElementById('impt').submit();
}
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  thinkphp phpexcel