我是 Laravel 的新手,目前使用的是版本 4.2。
我想要将一些数据导出为 PDF 和 Excel 文档。
在 Laravel 中有没有相关的方法呢?
我是 Laravel 的新手,目前使用的是版本 4.2。
我想要将一些数据导出为 PDF 和 Excel 文档。
在 Laravel 中有没有相关的方法呢?
<?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');
使用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,
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')