码迷,mamicode.com
首页 > Web开发 > 详细

php导出数据到excel

时间:2020-07-15 15:06:52      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:pat   ima   iter   文件的   type   actor   tin   填充   http   

技术图片

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

require_once ‘./Classes/PHPExcel.php‘;
$obj = new PHPExcel();
$objSheet = $obj->getActiveSheet();   //获取sheet操作对象
$objSheet->setTitle(‘demo‘);         //给当前sheet设置名称
//填充数据
$objSheet->setCellValue("A1","姓名")->setCellValue("B1","分数");
$objSheet->setCellValue("A2","za_szbyko")->setCellValue("B2","60");
//按照指定个是生成excel
$objWrite = PHPExcel_IOFactory::createWriter($obj, ‘Excel2007‘);
$_savePath = ‘abc‘.‘.xlsx‘;
$objWrite->save($_savePath);


//创建多sheet
require_once ‘./Classes/PHPExcel.php‘;
$data=array(
    array(
        ‘name‘=>‘张三‘,
        ‘score‘=>80,
        ‘banji‘=>‘一班‘,
    ),
    array(
        ‘name‘=>‘张四‘,
        ‘score‘=>90,
        ‘banji‘=>‘二班‘,
    ),
    array(
        ‘name‘=>‘张五‘,
        ‘score‘=>100,
        ‘banji‘=>‘三班‘,
    ),
);

$obj = new PHPExcel();

for($i=1;$i<=3;$i++){
    if($i>1){
        $obj->createSheet();//创建新的内置表
    }
    $obj->setActiveSheetIndex($i-1);//把新创建的sheet设定为当前活动sheet
    $objSheet = $obj->getActiveSheet();//获取当前活动sheet
    $objSheet->setTitle($i."年级");//当前活动sheet起名称
    $objSheet->setCellValue(‘A1‘, ‘姓名‘)->setCellValue(‘B1‘, ‘分数‘)->setCellValue(‘c1‘, ‘班级‘);//填充数据
    $j=2;
    foreach($data as $key=>$val){
        $objSheet->setCellValue(‘A‘.$j, $val[‘name‘])->setCellValue(‘B‘.$j,$val[‘score‘])->setCellValue(‘c‘.$j, $val[‘banji‘]);
        $j++;
    }
}

$objWrite = PHPExcel_IOFactory::createWriter($obj, ‘Excel5‘);
$_savePath = ‘abc‘.‘.xls‘;
//$objWrite->save($_savePath);  保存文件

/输出到浏览器
browser_export(‘Excel5‘,$_savePath);
$objWrite->save(‘php://output‘);

//输出excel 文件到浏览器
function browser_export($type,$filename){
    if($type=="Excel5"){
        header(‘Content-Type: application/vnd.ms-excel‘); //告诉浏览器将要输出excel03文件
    }else{
        header(‘Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet‘);//告诉浏览器数据excel07文件
    }
    header(‘Content-Disposition: attachment;filename="‘.$filename.‘"‘);  //告诉浏览器将输出文件的名称
    header(‘Cache-Control: max-age=0‘);  //禁止缓存
}

 

php导出数据到excel

标签:pat   ima   iter   文件的   type   actor   tin   填充   http   

原文地址:https://www.cnblogs.com/mengor/p/13304635.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!