本文链接:https://www.cnblogs.com/tujia/p/11358096.html

说明:简单好用的导出助手,轻松导出数据到 excel !!

使用示例1:

使用示例2:

使用示例3:

源码:

<?php
namespace common\helpers; use yii\helpers\ArrayHelper; /**
* Excel 助手
*/
class ExcelHelper
{
public static $styleFormat = []; /**
* @see \PHPExcel_Style_NumberFormat
*/
public static function setStyleFormat($format)
{
self::$styleFormat = $format;
} /**
* 导出
* @see https://www.cnblogs.com/tujia/p/11358096.html
* @param array $titles 标题,一维数组,可传map或单纯标题
* @param array $dataArray 数据,二维数组,可传map或单纯数据
* @param string $filename 文件名,要带后缀
* @param string $bigTitle 居中加粗的大标题,默认为空
* @param array $extra 扩展数据
* @return file
*/
public static function export(array $titles, $dataArray, $filename, $bigTitle='', $extra=[])
{
set_time_limit(0);
ini_set('memory_limit', '512M'); // 后缀
$suffix = substr($filename, strrpos($filename, '.'));
empty($titles) && die('标题数组不能为空!');
empty($dataArray) && die('数据数组不能为空!');
!in_array($suffix, ['.xls', '.xlsx']) && die('文件名格式错误!'); $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;
$cacheSettings = array('memoryCacheSize ' => '512MB');
\PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings); $oExcel = new \PHPExcel();
$oExcel->setActiveSheetIndex(0);
$sheet = $oExcel->getActiveSheet(); // 设置列数据格式
if (!empty(self::$styleFormat)) {
$fields = array_keys($titles);
foreach (self::$styleFormat as $field => $formatCode) {
$offset = array_search($field, $fields);
$col = chr(65+$offset);
$sheet->getStyle($col)->getNumberFormat()->setFormatCode($formatCode);
}
} // 行索引
$rowIndex = $bigTitle!=''? 2:1; $chr = [
'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'
]; // 设置大标题
if ($bigTitle != '') {
$sheet->mergeCells('A1:'. $chr[count($titles)-1] .'1');
$sheet->getStyle('A1')->applyFromArray([
'font' => ['bold'=>true],
'alignment' => ['horizontal'=>\PHPExcel_Style_Alignment::HORIZONTAL_CENTER]
]);
$sheet->setCellValue('A1', $bigTitle);
} // 设置标题 A1 B1 C1 ....
$colIndex = 0;
$fieldsMap = [];
foreach ($titles as $key => $title) {
$fieldsMap[] = $key;
$sheet->setCellValue($chr[$colIndex] . $rowIndex, $title);
$colIndex++;
} // 设置内容 A1 B1 C1 .... A2 B2 C2 ....
$rowIndex++;
foreach ($dataArray as $key => $value)
{
foreach ($fieldsMap as $colIndex => $field) {
if (strrpos($field, '|') !== false) {
$temp1 = explode('|', $field);
$pos = strrpos($temp1[1], '.');
$pos === false && $pos = strlen($temp1[1]);
$temp2 = [];
$temp2[0] = substr($temp1[1], 0, $pos);
$temp2[1] = substr($temp1[1], $pos+1);
$val = $value[$temp1[0]];
$val = self::$temp2[0]($extra, $temp2[1], $val);
} else {
$val = $field? $value[$field] : $value;
}
$sheet->setCellValue($chr[$colIndex].$rowIndex, $val);
}
$rowIndex++;
} header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
if ($suffix == '.xlsx') {
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
} else {
header('Content-Type: application/vnd.ms-excel');
}
header('Content-Disposition: attachment;filename="'. $filename .'"');
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
$oWriter = \PHPExcel_IOFactory::createWriter($oExcel, 'Excel2007');
$oWriter->save('php://output');
$oExcel->disconnectWorksheets();
exit;
} /**
* 导出
* @see https://www.cnblogs.com/tujia/p/5999806.html
* @param array $titles 标题,一维数组,可传map或单纯标题
* @param array $dataArray 数据,二维数组,可传map或单纯数据
* @param string $filename 文件名,要带后缀
* @param array $extra 扩展数据
* @return file
*/
public static function exportSimple(array $titles, $dataArray, $filename, $extra=[])
{
// 后缀
$suffix = substr($filename, strrpos($filename, '.'));
empty($titles) && die('标题数组不能为空!');
empty($dataArray) && die('数据数组不能为空!');
!in_array($suffix, ['.xls', '.xlsx', '.csv']) && die('文件名格式错误!'); // 导出准备
set_time_limit(0);
ini_set('memory_limit', '512M'); header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Disposition: attachment; filename='.$filename);
if ($suffix == '.xlsx') {
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
} elseif ($suffix == '.xls') {
header('Content-Type: application/vnd.ms-excel');
} elseif ($suffix == '.csv') {
header('Content-Type: application/vnd.ms-excel; charset=GB2312');
}
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache"); $isCsv = ($suffix == '.csv');
$fieldsCount = count($titles);
if ($isCsv) {
echo mb_convert_encoding(implode(',', array_values($titles)), 'gbk') . "\n";
} else {
echo '<table>';
echo '<tr>';
foreach ($titles as $key => $value) {
echo sprintf('<td>%s</td>', $value);
}
echo '</tr>';
} foreach ($dataArray as $key => $value) {
$i = 0;
$isCsv==false && print('<tr>');
foreach ($titles as $field => $title) {
if (strrpos($field, '|') !== false) {
$temp1 = explode('|', $field);
$pos = strrpos($temp1[1], '.');
$pos === false && $pos = strlen($temp1[1]);
$temp2 = [];
$temp2[0] = substr($temp1[1], 0, $pos);
$temp2[1] = substr($temp1[1], $pos+1);
$val = $value[$temp1[0]];
$val = self::$temp2[0]($extra, $temp2[1], $val);
} else {
$val = $field? $value[$field] : $value;
} if ($isCsv) {
echo mb_convert_encoding($val . ($i == $fieldsCount-1? "\n":','), 'gbk');
} else {
if (isset(self::$styleFormat[$field])) {
echo sprintf("<td style='mso-number-format:\"%s\";'>%s</td>", self::$styleFormat[$field], $val);
} else {
echo sprintf('<td>%s</td>', $val);
}
}
$i++;
}
$isCsv==false && print('</tr>');
}
$isCsv==false && print('</table>');
exit;
} public static function extra($extra, $extra_key, $val)
{
$arr = ArrayHelper::getValue($extra, $extra_key, []);
return ArrayHelper::getValue($arr, $val, '');
} public static function dateIsEmpty($extra, $extra_key, $val)
{
return strtotime($val)>1000? $val:'';
} public static function toFixed($extra, $extra_key, $val)
{
return (string)sprintf("%.{$extra_key}f", floatval($val));
} public static function dateFormat($extra, $extra_key, $val)
{
return date('Y-m-d H:i:s',$val/1000);
} public static function trim($extra, $extra_key, $val)
{
return str_replace(["\r", "\n", ","], ["", "", ","], $val);
}
}

原创内容,转载请声明出处!

本文链接:https://www.cnblogs.com/tujia/p/11358096.html

PHPExcel 导出数据(xls或xlsx)- 助手类(函数)的更多相关文章

  1. php利用phpexcel导出数据

    php中利用phpexcel导出数据的实现代码.对phpexcel类库不熟悉的朋友,可以阅读下<phpexcel中文帮助手册>中的内容,具体实例大家可以phpexcel快速开发指南中的相关 ...

  2. php 使用PHPExcel 导出数据为Excel

    <?php require_once 'PHPExcel/Classes/PHPExcel.php'; /** * 导出数据为Excel * @param array $fieldArr 标题数 ...

  3. Thinkphp解决phpExcel导出数据量大导致内存溢出

    工作需要导出几万的数据量.操作比较频繁.之前数据在七八千是数据导出很慢.phpExcel是方便但是性能一般.现在改为使用csv导出数据:可以缓解内存压力,一次导出两三万是没问题的.当然服务器内存给力, ...

  4. phpexcel导出数据 出现Formula Error的解决方案

    phpexcel导出数据报错 Uncaught exception 'Exception' with message 'Sheet1!A1364 -> Formula Error: Unexpe ...

  5. phpexcel导出数据表格

    1.下载phpexcel(李昌辉) 2.在页面引入phpexcel的类文件,并且造该类的对象 include("../chajian/phpexcel/Classes/PHPExcel.ph ...

  6. thinkphp中使用PHPEXCEL导出数据

    thinkphp中导出二维数组到Excel 1.解决时间长度导致EXCEL出现###问题 2.解决长数值型 带来的科学记数法导出问题 订单号不再变为科学记数法 而是直接字符串类型 代码如下: < ...

  7. PHP:引用PhpExcel导出数据到excel表格

    我使用的是tp3.2框架(下载地址:http://www.thinkphp.cn/topic/38123.html) 1.首先要下载PhpExcel类库,放在如下图目录下 2.调用方法 public ...

  8. C#自定义导出数据到Excel中的类封装

    using System; using System.IO; using System.Data; using System.Collections; using System.Data.OleDb; ...

  9. 使用PHPExcel导出数据

    最近要求做增加客流数据等导出为Excel的功能,phpExcel包功能强大,根据实际需求,我只学习了简单的功能. 安装PHPExcel 在composer.json中添加: "require ...

随机推荐

  1. Spring Boot 日志管理

    Spring Boot 日志管理 网址 Spring Boot 日志管理 http://blog.didispace.com/springbootlog/ Spring Boot快速入门(四)--日志 ...

  2. wordpress导航当前页面菜单高亮显示如何操作

    我们在制作wordpress主题时有些客户要求导航在访问某个菜单时,这个菜单项会高亮显示,让用户知道自己正在访问的是哪个菜单下的内容,这个要如何实现呢?wordpress早就为你想好了,.curren ...

  3. Mac下用java代码调用adb命令时出错

    原本我直接这样写: Process process=Runtime.getRuntime().exec("adb devices"); 但是运行时出错: java.io.IOExc ...

  4. router.beforeEach、路由元信息、导航守卫与函数式编程

    一.函数的识别: 1.router.beforeEach:主函数.高阶函数.入口函数: 2.匿名参量函数:处理跳转过程中的附加逻辑 (to, from, next) => { if (to.ma ...

  5. MongoDB db.stats()&&db.db.serverStatus()

    db.stats()   示例图 参数解释: "db" : "test" ,表示当前是针对"test"这个数据库的描述.想要查看其他数据库, ...

  6. js中call,apply,bind方法的用法

    call .apply.和bind 以上这三个方法都是js function函数当中自带的方法,用来改变当前函数this的指向. call()方法 语法格式: fun.call(thisArg[,ar ...

  7. typedi 强大的javascript以及typescript 依赖注入框架

    typedi 是typestack团队提供的依赖注入解决方案,对于typescript 我们可以使用注解的开发方式,官方的文档也比较详细 javascript 使用 基于函数的服务注入 var Ser ...

  8. .Net 下基于Redlock redis 分布式锁实现

    Redlock-cs (C#/.NET implementation). RedLock.net (C#/.NET implementation). Includes async and lock e ...

  9. bzoj4066: 简单题 K-Dtree

    bzoj4066: 简单题 链接 bzoj 思路 强制在线.k-dtree. 卡常啊.空间开1e6就T了. 代码 #include <bits/stdc++.h> #define my_m ...

  10. 【题解】洛谷 P1080 国王游戏

    目录 题目 思路 \(Code\) 题目 P1080 国王游戏 思路 贪心+高精度.按\(a \times b\)从小到大排序就可以了. \(Code\) #include<bits/stdc+ ...