您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ExportService.php 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Services;
  3. use App\Contracts\ExportableReport;
  4. use App\Models\Company;
  5. use Barryvdh\DomPDF\Facade\Pdf;
  6. use Illuminate\Support\Carbon;
  7. use Symfony\Component\HttpFoundation\StreamedResponse;
  8. class ExportService
  9. {
  10. public function exportToCsv(Company $company, ExportableReport $report, string $startDate, string $endDate): StreamedResponse
  11. {
  12. $filename = $company->name . ' ' . $report->getTitle() . ' ' . $startDate . ' to ' . $endDate . '.csv';
  13. $headers = [
  14. 'Content-Type' => 'text/csv',
  15. 'Content-Disposition' => 'attachment; filename="' . $filename . '"',
  16. ];
  17. $callback = function () use ($report, $company, $startDate, $endDate) {
  18. $file = fopen('php://output', 'wb');
  19. fputcsv($file, [$report->getTitle()]);
  20. fputcsv($file, [$company->name]);
  21. fputcsv($file, ['Date Range: ' . $startDate . ' to ' . $endDate]);
  22. fputcsv($file, []);
  23. fputcsv($file, $report->getHeaders());
  24. foreach ($report->getCategories() as $category) {
  25. fputcsv($file, $category->header);
  26. foreach ($category->data as $accountRow) {
  27. fputcsv($file, $accountRow);
  28. }
  29. fputcsv($file, $category->summary);
  30. fputcsv($file, []); // Empty row for spacing
  31. }
  32. fputcsv($file, $report->getOverallTotals());
  33. fclose($file);
  34. };
  35. return response()->streamDownload($callback, $filename, $headers);
  36. }
  37. public function exportToPdf(Company $company, ExportableReport $report, string $startDate, string $endDate): StreamedResponse
  38. {
  39. $pdf = Pdf::loadView('components.company.reports.report-pdf', [
  40. 'company' => $company,
  41. 'report' => $report,
  42. 'startDate' => Carbon::parse($startDate)->format('M d, Y'),
  43. 'endDate' => Carbon::parse($endDate)->format('M d, Y'),
  44. ])->setPaper('a4');
  45. return response()->streamDownload(function () use ($pdf) {
  46. echo $pdf->stream();
  47. }, strtolower(str_replace(' ', '-', $company->name . '-' . $report->getTitle())) . '.pdf');
  48. }
  49. }