热门IT资讯网

tp5封装 phpexecl引入和调用类的封装以及调用

发表于:2024-11-25 作者:热门IT资讯网编辑
编辑最后更新 2024年11月25日,composer安装phpexeclcomposer require phpoffice/phpexcel

composer安装phpexecl

composer require phpoffice/phpexcel


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;

}

}



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: p_w_upload;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();

}


0