用PhpSpreadsheet读取xlsx表格模板进行数据导出

/**
     * @param array $dataList 数据列表,为数字索引
     * @param string $title 导出文件名
     * @param string $tpl excel的模板文件
     * @param int $begin 模板的数据起始行数,从1开始计数除去header的行
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public static function CustomSaveExcel($dataList=[],$title,$tpl='',$begin=0){
        if(!$tpl||!is_file($tpl)){
            throw new \Exception("模板文件不存在!");
        }
        //引入核心文件
        ini_set('memory_limit','1024M');
        // 要读取的文件的路径
        $spreadSheet = IOFactory::load($tpl);
        $letter = array('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','ZZ','BA','BB','BC','BD','BE','BF','BG','BH','BI','BJ','BK','BL','BM','BN','BO','BP','BQ','BR','BS','BT','BU','BV');
        $spreadSheet->setActiveSheetIndex(0);
        foreach ($dataList as $key => $row) {

            $newobj =  $spreadSheet->setActiveSheetIndex(0);
            foreach ($row as $rowInex => $rowValue) {
                $index = $letter[$rowInex].($begin);
                static::dealVal($rowValue);
                if(is_numeric($rowValue) && !is_float($rowValue) && !is_double($rowValue) && strlen($rowValue)>10){
                    $newobj->setCellValueExplicit($index, $rowValue, DataType::TYPE_STRING);
                }
                else{
                    $newobj->setCellValue($index, $rowValue);
                }

                $newobj->getStyle($index)->getAlignment()->setWrapText(true);
            }
            $begin++;
        }
        ob_end_clean();
        header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        header("Content-Disposition: inline;filename=\"".$title.".xlsx\"");
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($spreadSheet, 'Xlsx');
        $objWriter->save('php://output');
    }

    public static function dealVal(&$val){
        if(strtolower($val)===null||(is_numeric($val)&&$val == 0)){
            $val = '/';
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

文竹、文竹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值