使用phpexcel将excel文件转换为pdf,返回空文件

时间:2017-07-28 06:17:14

标签: php excel pdf yii2 phpexcel

我有一个excel文件,我想使用php excel将文件转换为pdf。使用以下代码:

namespace frontend\controllers;
use PHPExcel;
use PHPExcel_IOFactory;
use PHPExcel_Settings;
use PHPExcel_Style_Alignment;
use yii\web\Controller;

class ExportsController extends Controller
{
    public function actionIndex()
    {
        $inputFile = \Yii::getAlias('@frontend') . '/controllers/matrix.xls';
        $inputFileType = PHPExcel_IOFactory::identify($inputFile);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFile);
        $objPHPExcel->setActiveSheetIndex(0);

        $rendererLibrary = 'DomPDF';
        $rendererLibraryPath = \Yii::getAlias('@frontend') . '/components/Classes/PHPExcel/Writer/PDF/' . $rendererLibrary;
        $rendererLibraryPath .= '.php';

        if (!PHPExcel_Settings::setPdfRenderer(
            $rendererLibrary,
            $rendererLibraryPath
        )
        ) {
            die(
                'NOTICE: Please set the $rendererName and $rendererLibraryPath values' .
                '<br />' .
                'at the top of this script as appropriate for your directory structure'
            );
        }
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment;filename="01simple.pdf"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
        $objWriter->save('php://output');
    }
}

当我评论最后两行代码时,它返回空的pdf文件,否则会抛出以下错误:net::ERR_INVALID_RESPONSE

你能帮我找一下代码的错误吗?

2 个答案:

答案 0 :(得分:0)

在最后添加此代码

  header('Content-Type: application/pdf');
  header('Content-Disposition: attachment;filename="01simple.pdf"');
  header('Cache-Control: max-age=0');
  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
  ob_end_clean();
  $objWriter->save('php://output');

答案 1 :(得分:0)

如果你的xls文件有超过3000条记录,DomPDF将产生内存错误。