Laravel EXCEL 和 PDF 导出

3

我是 Laravel 的新手,目前使用的是版本 4.2。

我想要将一些数据导出为 PDF 和 Excel 文档。

在 Laravel 中有没有相关的方法呢?

2个回答

7
使用FPDF来完成您所需的操作。您需要从头开始创建PDF文件,并以您想要的方式填充它。
<?php
require('fpdf.php');

$pdf = new FPDF();
$pdf->AddPage();    // add page to PDF
$pdf->SetFont('Arial','B',16);    // Choose a font and size
$pdf->Cell(40,10,'Hello World!');  // write anything to any line you want
$pdf->Output("your_name.pdf");   // Export the file and send in to browser       
?>

对于Excel,一种简单的方式是将PHPExcel添加到Laravel中。只需将以下行添加到您的composer.json文件中:

"require": {
    "phpexcel/phpexcel": "dev-master"
}

然后运行composer update。使用方式如下:

$ea = new PHPExcel();

$ea->getProperties()
   ->setCreator('somebody')
   ->setTitle('PHPExcel Demo')
   ->setLastModifiedBy('soembody')
   ->setDescription('A demo to show how to use PHPExcel to manipulate an Excel file')
   ->setSubject('PHP Excel manipulation')
   ->setKeywords('excel php office phpexcel')
   ->setCategory('programming')
   ;

$ews = $ea->getSheet(0);
$ews->setTitle('Data');

$ews->setCellValue('a1', 'ID'); // Sets cell 'a1' to value 'ID 
$ews->setCellValue('b1', 'Season');

你如何将Excel导出为PDF? - tjvg1991
@Peyman.H 如果我使用像这个这样的jQuery插件来导出Excel和PDF,那么会有什么问题吗?有人能推荐一个最好的专业jQuery插件来导出Excel(xlsx)和PDF吗? - developer

4

使用maatwebsite来创建和导入Excel、CSV和PDF文件。

将以下行添加到您的composer.json中:

"require": {
   "maatwebsite/excel": "~2.1.0"
}

在更新Composer后,将ServiceProvider添加到config/app.php文件中的providers数组中。

Maatwebsite\Excel\ExcelServiceProvider::class,

您可以使用门面模式来缩短代码。将以下内容添加到您的别名中:
'Excel' => Maatwebsite\Excel\Facades\Excel::class,

在 Laravel 5 中发布配置设置,请使用以下代码:
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

这个包的简单使用方法:

    $users = User::select('id','name' ,'username')->get();
    $Info = array();
    array_push($Info, ['id','name' ,'username']);
    foreach ($users as $user) {
        array_push($Info, $user->toArray());
    }
    Excel::create('Users', function($excel) use ($Info) {

        $excel->setTitle('Users');
        $excel->setCreator('milad')->setCompany('Test');
        $excel->setDescription('users file'); 
        $excel->sheet('sheet1', function($sheet) use ($Info) {
            $sheet->setRightToLeft(true);
            $sheet->fromArray($Info, null, 'A1', false, false);
        });

    })->download('xls'); // or download('PDF')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接