多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 目录 [TOC=2,3] * * * * * * * * * * * * * * * * * * * * - ## PHPExcel函数集合 * * * * * * * * * * * * * * * - ### 读取excel里的数据到数组中 * * * * * >[info]#### 1. 读取excel里的数据到数组中【read】 ~~~ 方法一: /** * 读取excel里的数据到数组中 * @param: $filename 路径文件名 * @param:$encode 返回数据的编码 默认为utf8 * @author: ityangs<ityangs@163.com> */ public function read($filename,$encode='utf-8'){ $type = 'Excel5'; if(strtolower(array_pop(explode('.',$filename))) == 'xlsx'){ $type = 'Excel2007'; } $objPHPExcel = new PHPExcel(); $objReader = PHPExcel_IOFactory::createReader($type); $objReader->setReadDataOnly(true); $objPHPExcel = $objReader->load($filename); // $objWorksheet = $objPHPExcel->getActiveSheet(); $objSheet = $objPHPExcel->getAllSheets(); $excelData = array(); foreach($objSheet as $k=>$sheet){ $highestRow = $sheet->getHighestRow(); $highestColumn = $sheet->getHighestColumn(); $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); for ($row = 1; $row <= $highestRow; $row++) { for ($col = 0; $col < $highestColumnIndex; $col++) { $excelData[$k]['list'][$row-1][] =(string)$sheet->getCellByColumnAndRow($col, $row)->getValue(); } } $excelData[$k]['title'] = $sheet->getTitle(); } return $excelData; } 方法二: /** * 读取excel里的数据到数组中 * @param: $filename 路径文件名 * @param:$encode 返回数据的编码 默认为utf8 * @author: ityangs<ityangs@163.com> */ public function read($filename,$encode='utf-8'){ $excel=PHPExcel_IOFactory::load($filename); $excel->setActiveSheetIndex(0); $sheetData = $excel->getActiveSheet()->toArray(null,true,true,true); unlink($filename); unset($sheetData[1]); return $excelData; } ~~~ >[info]#### 2. 测试 - #### 函数使用 ~~~ read($path); ~~~ - #### 函数结果 ~~~ <pre>Array ( [0] => Array ( [list] => Array ( [0] => Array ( [0] => 发货单号 [1] => 更改后渠道代码 [2] => 更改后计费重 [3] => 更改后总费用 [4] => 更改原因 ) [1] => Array ( [0] => FH171227000003 [1] => QD00323 [2] => 12 [3] => 12 [4] => 清关原因 ) ) [title] => Sheet1 ) ) </pre> ~~~ * * * * * * * * * * * * * * * - ### 读取excel文件的日期转换成php时间 * * * * * >[info]#### 1.读取excel文件的日期转换成php时间【excelTime】 ~~~ /** * 读取excel文件的日期转换成php时间 * @param $date * @param bool|false $time * @return array|int|string */ protected function excelTime($date, $time = false) { if(function_exists('GregorianToJD')){ if (is_numeric( $date )) { $jd = GregorianToJD( 1, 1, 1970 ); $gregorian = JDToGregorian( $jd + intval ( $date ) - 25569 ); $date = explode( '/', $gregorian ); $date_str = str_pad( $date [2], 4, '0', STR_PAD_LEFT ) ."-". str_pad( $date [0], 2, '0', STR_PAD_LEFT ) ."-". str_pad( $date [1], 2, '0', STR_PAD_LEFT ) . ($time ? " 00:00:00" : ''); return $date_str; } }else{ $date=$date>25568?$date+1:25569; /*There was a bug if Converting date before 1-1-1970 (tstamp 0)*/ $ofs=(70 * 365 + 17+2) * 86400; $date = date("Y-m-d",($date * 86400) - $ofs).($time ? " 00:00:00" : ''); } return $date; } ~~~ >[info]#### 2. 测试 - #### 函数使用 ~~~ excelTime($data); ~~~ - #### 函数结果 ~~~ 2018-01-01 00:00:00 ~~~ * * * * * * * * * * * * * * * - ## PHP操作导入导出Excel和CSV函数 * * * * * >[info]#### 2. 导出Excel文件【export_excel】 ~~~ /** *导出Excel表格 *@param $data 一个二维数组,结构如同从数据库查出来的数组 *@param $title excel的第一行标题,一个数组,如果为空则没有标题 *@param $filename 下载的文件名 为空是当前时间格式命名 *@param $filetype 下载的文件类型(支持:xls/xlsx) *@param int $limit 每隔$limit行 刷新一下输出buffer,不要太大,也不要太小 *@examlpe *export_excel($arr,array('id','账户','密码','昵称'),'文件名','xls',10000); */ function export_excel($data=array(),$title=array(),$filename='',$filetype='xls',$limit=10000) { ignore_user_abort(true); set_time_limit(0);// 不限制脚本执行时间以确保导出完成 ini_set("memory_limit","1024M"); $filename=!empty($filename)?$filename:date('YmdHis',time()); header("Content-type:application/octet-stream"); header("Accept-Ranges:bytes"); header("Content-type:application/vnd.ms-excel"); header("Content-Disposition:attachment;filename={$filename}.{$filetype}"); header("Pragma: no-cache"); header("Expires: 0"); //导出开始 if (count($title)>0) { foreach ($title as $k => $v) { $title[$k]=iconv("utf-8", "gbk",$v); } $title= implode("\t ", $title); echo "$title\n"; } $num = 0; if (count($data)>0) { foreach($data as $key=>$val) { $num++; //刷新一下输出buffer,防止由于数据过多造成问题 if ($limit == $num) { ob_flush(); flush(); $num = 0; } foreach ($val as $ck => $cv) { $data[$key][$ck]=iconv("utf-8", "gbk", $cv); } $data[$key]=implode("\t ", $data[$key]); } echo implode("\n",$data); } } ~~~ >[info]#### 2. 测试 - #### 函数使用 ~~~ $data=[ ['卡1','b',date("Y-m-d"),'d'], ['卡2','b','c','d'], ['卡3','b','c','d'], ['卡4','b','c','d'], ]; $title=array('卡','生成码','开始','有效'); export_excel($data, $title, 'test','xls',10000); ~~~ - #### 函数结果 ~~~ 导出Excel文件 ~~~ * * * * * * * * * * * * * * * >[info]#### 3. 导入CSV文件【import_csv】 ~~~ /** * 导入CSV文件 * @param string $csv_file csv文件路径 * @param int $offset 起始行数:1为标题行,跟EXcel行标对应 * @param int $lines 读取行数:-1(负数)为读完,正数为读取的行数 * @return array|bool */ function import_csv($csv_file = '', $offset = 1, $lines = -1) { ignore_user_abort(true); set_time_limit(0);// 不限制脚本执行时间以确保导出完成 ini_set("memory_limit","1024M"); if (!$fp = fopen($csv_file, 'r')) { return false; } $i = $j = 1; $data = array(); //过滤起始行以前的数据 while (false !== ($line = fgets($fp))) { if ($i++ < $offset) { continue; } $data[0]=explode(',', $line); break; } if ($lines<0){//读完 while (!feof($fp)) { $data[] = fgetcsv($fp); } }else { while ($j++ <= $lines && !feof($fp)) { $data[] = fgetcsv($fp); } } fclose($fp); array_pop($data);//删除数组最后一个空数组 return $data; } ~~~ >[info]#### 2. 测试 - #### 函数使用 ~~~ echo "<pre>"; print_r(import_csv('test.csv',3,2)); echo "</pre>"; ~~~ - #### 函数结果 ~~~ Array ( [0] => Array ( [0] => 卡2 [1] => b [2] => c [3] => d ) [1] => Array ( [0] => 卡3 [1] => b [2] => c [3] => d ) ) ~~~ * * * * * >[info]#### 4. 导出CSV文件【export_csv】 ~~~ /** * 导出CSV文件 * @param array $data 数据 * @param array $header_data 首行标题数据 * @param string $file_name 文件名称 为空是当前时间格式命名 * @param int $limit 每隔$limit行 刷新一下输出buffer,不要太大,也不要太小 * @return string */ function export_csv($data = [], $header_data = [], $file_name = '',$limit=10000) { ignore_user_abort(true); set_time_limit(0);// 不限制脚本执行时间以确保导出完成 ini_set("memory_limit","1024M"); $filename=!empty($filename)?$filename:date('YmdHis',time()); header("Content-type:application/octet-stream"); header("Accept-Ranges:bytes"); header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename='.$file_name.'.csv'); header('Cache-Control: max-age=0'); $fp = fopen('php://output', 'a'); //这个是后台生成文件(并去除header) //$file_path=$dir_path.'/'.$file_name.'.csv'; //$fp = fopen($file_path, 'a'); if (!empty($header_data)) { foreach ($header_data as $key => $value) { $header_data[$key] = iconv('utf-8', 'gbk', $value); } fputcsv($fp, $header_data); } $num = 0; //逐行取出数据,不浪费内存 $count = count($data); if ($count > 0) { for ($i = 0; $i < $count; $i++) { $num++; //刷新一下输出buffer,防止由于数据过多造成问题 if ($limit == $num) { ob_flush(); flush(); $num = 0; } $row = $data[$i]; foreach ($row as $key => $value) { $row[$key] = iconv('utf-8', 'gbk', $value); } fputcsv($fp, $row); } } fclose($fp); } ~~~ >[info]#### 2. 测试 - #### 函数使用 ~~~ $data=[ ['卡1','b','c','d'], ['卡2','b','c','d'], ['卡3','b','c','d'], ['卡4','b','c','d'], ]; $title=array('卡','生成码','开始','有效'); export_csv($data,$title,'test',1000); ~~~ - #### 函数结果 ~~~ 生成csv文件 ~~~ * * * * * * * * * * * * * * * >[info]#### 5. table导出CSV文件【exportExcel】 ~~~ /** * 导出数据 * @date: 2018年7月3日 下午5:21:52 * @author: ityangs<ityangs@163.com> */ function exportExcel($data=array(),$title=array(),$filename='',$filetype='xls') { set_time_limit(0);// 不限制脚本执行时间以确保导出完成 ini_set("memory_limit","1024M"); $filename=!empty($filename)?$filename:date('YmdHis',time()); header("Content-type:application/octet-stream"); header("Accept-Ranges:bytes"); header("Content-type:application/vnd.ms-excel"); header("Content-Disposition:attachment;filename={$filename}.{$filetype}"); header("Pragma: no-cache"); header("Expires: 0"); $content=""; $content.="<table border='1' align='center' style='font-size:15px;'><tr>"; foreach($title as $pre){ $content.="<td>$pre</td>"; } $content.="</tr>"; foreach($data as $list){ $content.= "<tr>"; foreach($list as $val){ $content.= "<td style='vnd.ms-excel.numberformat:@;width:150px;'>".$val."</td>"; //style样式将导出的内容都设置为文本格式 输出对应键名的键值 即内容 } $content.="</tr>"; } $content.="</table>"; echo $content; exit(); } ~~~ >[info]#### 2. 测试 - #### 函数使用 ~~~ exportExcel($data,$title,'用户信息导出',$filetype='xls'); ~~~ - #### 函数结果 ~~~ 生成Excel ~~~