PhpExcel.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace app\common\server;
  3. //use think\Log;
  4. use app\common\server\MyPhpOffacePsr16Implementation;
  5. //use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  6. use PhpOffice\PhpSpreadsheet\IOFactory;
  7. use PhpOffice\PhpSpreadsheet\Settings;
  8. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  9. /**
  10. * excel导出
  11. *
  12. * @Author wj
  13. * @DateTime 2022-10-02
  14. * @Describe
  15. */
  16. class PhpExcel
  17. {
  18. private $title;
  19. private $body;
  20. private $sheetobj;
  21. private $spreadsheet;
  22. public function __construct()
  23. {
  24. $this->spreadsheet = new Spreadsheet();
  25. $sheet = $this->spreadsheet->getActiveSheet();
  26. $this->sheetobj = $sheet;
  27. }
  28. public function settitle($title)
  29. {
  30. $this->title = $title;
  31. }
  32. public function setbody($body)
  33. {
  34. $this->body = $body;
  35. }
  36. /**
  37. * 自定义缓存
  38. *
  39. * @return void
  40. * @author wj
  41. * @date 2023-01-17
  42. */
  43. public function setmararycache()
  44. {
  45. $cache = new MyPhpOffacePsr16Implementation();
  46. Settings::setCache($cache);
  47. }
  48. public function getsheetobj($body, $title = [], $style = [], $newsheet = false)
  49. {
  50. if ($newsheet) {
  51. $sheetobj = $this->spreadsheet->createSheet();
  52. } else {
  53. $sheetobj = $this->sheetobj;
  54. }
  55. if (!empty($title)) {
  56. foreach ($title as $key => $value) {
  57. $sheetobj->getCell($value['cell'])->setValue($value['value']);
  58. }
  59. }
  60. foreach ($body as $key => $value) {
  61. foreach ($value as $k => $v) {
  62. $sheetobj->getCell($v['cell'])->setValue($v['value']);
  63. }
  64. }
  65. if (!empty($style)) {
  66. foreach ($style as $key => $value) {
  67. $sheetobjstyle = $sheetobj->getColumnDimension($key);
  68. foreach ($value as $k => $v) {
  69. switch ($k) {
  70. case 'width':
  71. $sheetobjstyle->setWidth($v);
  72. break;
  73. }
  74. }
  75. }
  76. }
  77. $this->sheetobj = $sheetobj;
  78. }
  79. public function exportsheet($filename, $type = "Xlsx")
  80. {
  81. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  82. header('Content-Disposition: attachment;filename=' . $filename);
  83. header('Cache-Control: max-age=0');
  84. // If you're serving to IE 9, then the following may be needed
  85. header('Cache-Control: max-age=1');
  86. header('Pragma: public'); // HTTP/1.0
  87. $objwriter = IOFactory::createWriter($this->spreadsheet, $type);
  88. $objwriter->save('php://output');
  89. }
  90. public function sevefile($filename, $type = "Xlsx")
  91. {
  92. $objwriter = IOFactory::createWriter($this->spreadsheet, $type);
  93. $objwriter->save($filename);
  94. }
  95. }