WithSheetTest.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace Tests\Exporters\CSV;
  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('csv');
  20. $sheet = Excel::createSheet($users)
  21. ->headingStyle(
  22. (new StyleBuilder)
  23. ->setFontColor(Color::BLUE)
  24. ->setFontSize(14)
  25. ->build()
  26. )
  27. ->row(function (array $row) {
  28. $style = (new StyleBuilder)
  29. ->setFontColor(Color::PURPLE)
  30. ->setFontSize(14)
  31. ->build();
  32. return WriterEntityFactory::createRowFromArray($row, $style);
  33. });
  34. // 保存
  35. Excel::export($sheet)->store($storePath);
  36. // 读取
  37. $this->assertSingleSheet($storePath, 0, $users);
  38. /*
  39. |---------------------------------------------------------------
  40. | 测试多个sheet
  41. |---------------------------------------------------------------
  42. */
  43. $users1 = new SheetCollection(array_slice($users, 0, 30));
  44. $users2 = new SheetCollection(array_values(array_slice($users, 30, 30)));
  45. $storePath = $this->generateTempFilePath('csv');
  46. $sheet1 = Excel::createSheet($users1, 'sheet1');
  47. $sheet2 = Excel::createSheet($users2, 'sheet2');
  48. // 保存
  49. Excel::export([$sheet1, $sheet2])->store($storePath);
  50. // 读取
  51. $this->assertSingleSheet($storePath, 0, $users);
  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('csv');
  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. // 读取
  68. $this->assertSingleSheet($storePath, 0, $users);
  69. }
  70. }