ExcelWriter.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace excel;
  3. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  4. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  5. class ExcelWriter
  6. {
  7. private $spreadsheet;
  8. private $sheet;
  9. private $fileUrl;
  10. public function __construct()
  11. {
  12. $this->spreadsheet = new Spreadsheet();
  13. $this->sheet = $this->spreadsheet->getActiveSheet();
  14. }
  15. public function setHeaders(array $headers, $row = 1)
  16. {
  17. foreach ($headers as $column => $header) {
  18. $this->sheet->setCellValue($this->getColumnLetter($column + 1) . $row, $header);
  19. }
  20. }
  21. public function addData(array $data, $startRow = 2)
  22. {
  23. foreach ($data as $rowIndex => $row) {
  24. foreach ($row as $column => $value) {
  25. $this->sheet->setCellValue($this->getColumnLetter($column + 1) . ($startRow + $rowIndex), $value);
  26. if (is_numeric($value) && strlen($value) > 10) {
  27. $this->sheet->getCell($this->getColumnLetter($column + 1) . ($startRow + $rowIndex))->setValueExplicit($value);
  28. }
  29. $this->sheet->getColumnDimension($this->getColumnLetter($column + 1))->setWidth(20);
  30. }
  31. }
  32. }
  33. public function save($filename)
  34. {
  35. $savePath = "./exports/";
  36. $filePath = $savePath . $filename;
  37. $writer = new Xlsx($this->spreadsheet);
  38. $writer->save($filePath);
  39. $this->fileUrl = "/exports/". $filename;
  40. }
  41. public function fileUrl()
  42. {
  43. return $this->fileUrl;
  44. }
  45. /**
  46. * 生成并保存 Excel 文件
  47. * @return void
  48. */
  49. function generateExcelFile(array $headers, array $lists,string $filename, array $map = [],string $suffix = 'xlsx'): void
  50. {
  51. //if(!in_array($suffix,['xlsx','xls'])) throw new \Exception('文件格式不正确');
  52. $this->setHeaders($headers);
  53. $data = array_map(function($row) use ($map) {
  54. if(empty($map)){
  55. return $row;
  56. }
  57. $tmp_arr = [];
  58. foreach ($map as $value){
  59. $tmp_arr[] = $row[$value];
  60. }
  61. return $tmp_arr;
  62. }, $lists);
  63. $this->addData($data);
  64. $this->save($filename.".".$suffix);
  65. }
  66. private function getColumnLetter($columnIndex)
  67. {
  68. return \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($columnIndex);
  69. }
  70. }