白狼栈 2016-04-16 17:11:24 5421次浏览 6条回复 9 4 0

作者:白狼 出处:http://www.manks.top/article/yii2_excel_extension 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

这里只简要说明重点,详细请看原文

第一步下载phpexcel 第二步调用下面的方法即可

下面是最终的解决方案,也是非常实用的数据导出方案

/**
     *  @DESC 数据导
     *  @notice 解决了上面导出列数过多的问题
     *  @example 
     *  $data = [1, '小明', '25'];
     *  $header = ['id', '姓名', '年龄'];
     *  Myhelpers::exportData($data, $header);
     *  @return void, Browser direct output
     */
    public static function exportData ($data, $header, $title = 'simple', $filename = 'data')
    {
        //require relation class files
        require(Yii::getAlias('@common').'/components/phpexcel/PHPExcel.php');
        require(Yii::getAlias('@common').'/components/phpexcel/PHPExcel/Writer/Excel2007.php');
    
        if (!is_array ($data) || !is_array ($header)) return false;

        $objPHPExcel = new \PHPExcel();

        // Set properties
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
        $objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
        $objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
        $objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
        $objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");

        // Add some data
        $objPHPExcel->setActiveSheetIndex(0);

        //添加头部
        $hk = 0;
        foreach ($header as $k => $v)
        {
            $colum = \PHPExcel_Cell::stringFromColumnIndex($hk);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
            $hk += 1;
        }

        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach($data as $key => $rows)  //行写入
        {
            $span = 0;
            foreach($rows as $keyName => $value) // 列写入
            {
                $j = \PHPExcel_Cell::stringFromColumnIndex($span);
                $objActSheet->setCellValue($j.$column, $value);
                $span++;
            }
            $column++;
        }

        // Rename sheet
        $objPHPExcel->getActiveSheet()->setTitle($title);

        // Save Excel 2007 file
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);

        header('Pragma:public');
        header("Content-Type:application/x-msexecl;name=\"{$filename}.xls\"");
        header("Content-Disposition:inline;filename=\"{$filename}.xls\"");

        $objWriter->save('php://output');
    
    }
觉得很赞
您需要登录后才可以回复。登录 | 立即注册