tp5封装 phpexecl引入和调用类的封装以及调用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了tp5封装 phpexecl引入和调用类的封装以及调用相关的知识,希望对你有一定的参考价值。
composer安装phpexecl
composer require phpoffice/phpexcel
<?php
namespace Potting;
use PHPExcel;
use PHPExcel_IOFactory;
class Excel
{
static public function export($headArr,$data){
$path=‘execl/‘;
$fileName=time();
if(!file_exists($path)){
mkdir($path,0777,true);
}
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties();
$key = ord("A"); // 设置表头
foreach ($headArr as $v) {
$colum = chr($key);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . ‘1‘, $v);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . ‘1‘, $v);
$key += 1;
}
$column = ‘2‘;
$objActSheet = $objPHPExcel->getActiveSheet();
foreach ($data as $key => $rows) { // 行写入
$span = ord("A");
foreach ($rows as $keyName => $value) { // 列写入
$objActSheet->setCellValue(chr($span) . $column, $value);
$span++;
}
$column++;
}
$fileName = $fileName.".xls";
$objActSheet = PHPExcel_IOFactory::createWriter($objPHPExcel,‘Excel2007‘);
//保存xls
$objActSheet->save($path.$fileName);
//返回路径
return $path.$fileName;
}
}
<?php
namespace Potting;
use PHPExcel;
use PHPExcel_IOFactory;
class Excel
{
static public function export($fileName,$headArr,$data){
// $path=‘execl/‘;
// $fileName=time();
// if(!file_exists($path)){
// mkdir($path,0777,true);
// }
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties();
$key = ord("A"); // 设置表头
foreach ($headArr as $v) {
$colum = chr($key);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . ‘1‘, $v);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . ‘1‘, $v);
$key += 1;
}
$column = ‘2‘;
$objActSheet = $objPHPExcel->getActiveSheet();
foreach ($data as $key => $rows) { // 行写入
$span = ord("A");
foreach ($rows as $keyName => $value) { // 列写入
$objActSheet->setCellValue(chr($span) . $column, $value);
$span++;
}
$column++;
}
$fileName = $fileName.".xls";
$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
$objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
header(‘Content-Type: application/vnd.ms-excel‘);
header("Content-Disposition: attachment;filename=‘$fileName‘");
header(‘Cache-Control: max-age=0‘);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel5‘);
$objWriter->save(‘php://output‘); // 文件通过浏览器下载
exit();
//$fileName = $fileName.".xls";
//$objActSheet = PHPExcel_IOFactory::createWriter($objPHPExcel,‘Excel2007‘);
//保存xls
//$objActSheet->save($path.$fileName);
//返回路径
//return $path.$fileName;
}
}
public function index()
{
$fileName=‘测试‘;
$header=[‘表头A‘,‘表头B‘,‘表头C‘];
$data=[
[‘嘿嘿‘,‘heihei‘,‘2321312‘],
[‘嘿嘿‘,‘heihei‘,‘2321312‘],
[‘哈哈‘,‘haha‘,‘2321312‘]
];
$url=Excel::export($fileName,$header,$data);
var_dump($url);die();
}
本文出自 “伤痕” 博客,请务必保留此出处http://9934547.blog.51cto.com/9924547/1979387
以上是关于tp5封装 phpexecl引入和调用类的封装以及调用的主要内容,如果未能解决你的问题,请参考以下文章