WithSheetTest.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace Tests\Exporters\XLSX;
  3. use Box\Spout\Common\Entity\Style\Color;
  4. use Box\Spout\Writer\Common\Creator\Style\StyleBuilder;
  5. use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
  6. use Dcat\EasyExcel\Excel;
  7. use Dcat\EasyExcel\Support\SheetCollection;
  8. use Tests\Exporters\Exporter;
  9. use Tests\TestCase;
  10. class WithSheetTest extends TestCase
  11. {
  12. use Exporter;
  13. /**
  14. * @group exporter
  15. */
  16. public function test()
  17. {
  18. $users = include __DIR__.'/../../resources/users.php';
  19. $storePath = $this->generateTempFilePath('xlsx');
  20. $sheet = Excel::createSheet($users)
  21. ->name('test')
  22. ->headingStyle(
  23. (new StyleBuilder)
  24. ->setFontColor(Color::BLUE)
  25. ->setFontSize(14)
  26. ->build()
  27. )
  28. ->row(function (array $row) {
  29. $style = (new StyleBuilder)
  30. ->setFontColor(Color::PURPLE)
  31. ->setFontSize(14)
  32. ->build();
  33. return WriterEntityFactory::createRowFromArray($row, $style);
  34. });
  35. // 保存
  36. Excel::export($sheet)->store($storePath);
  37. // 读取
  38. $this->assertSingleSheet($storePath, 'test', $users);
  39. /*
  40. |---------------------------------------------------------------
  41. | 测试多个sheet
  42. |---------------------------------------------------------------
  43. */
  44. $users1 = new SheetCollection(array_slice($users, 0, 30));
  45. $users2 = new SheetCollection(array_values(array_slice($users, 30, 30)));
  46. $storePath = $this->generateTempFilePath('xlsx');
  47. $sheet1 = Excel::createSheet($users1, 'sheet1');
  48. $sheet2 = Excel::createSheet($users2, 'sheet2');
  49. // 保存
  50. Excel::export([$sheet1, $sheet2])->store($storePath);
  51. $this->assertSheets($storePath, $users1->toArray(), $users2->toArray());
  52. }
  53. public function testWithChunkQuery()
  54. {
  55. $users = include __DIR__.'/../../resources/users.php';
  56. $users1 = new SheetCollection(array_slice($users, 0, 30));
  57. $users2 = new SheetCollection(array_values(array_slice($users, 30, 30)));
  58. $storePath = $this->generateTempFilePath('xlsx');
  59. $sheet1 = Excel::createSheet()->name('sheet1')->chunk(function (int $times) use ($users1) {
  60. return $users1->forPage($times, 10);
  61. });
  62. $sheet2 = Excel::createSheet()->name('sheet2')->chunk(function (int $times) use ($users2) {
  63. return $users2->forPage($times, 10);
  64. });
  65. // 保存
  66. Excel::export([$sheet1, $sheet2])->store($storePath);
  67. $this->assertSheets($storePath, $users1->toArray(), $users2->toArray());
  68. }
  69. }