updated US CDC website link to current immunization VIS page (#7855)
[openemr.git] / src / Services / SpreadSheetService.php
blobec087c5e4690bd63b223d0b8242b78433567cbe2
1 <?php
3 /**
4 * Spreadsheet service
6 * Takes a key -> value array where the keys are the column names
7 * and downloads a csv spreadsheet to the browser. Optionally send in
8 * a fields array to select only those columns would like to export.
10 * @package OpenEMR
11 * @link http://www.open-emr.org
12 * @author Sherwin Gaddis <sherwingaddis@gmail.com>
13 * @author Stephen Waite <stephen.waite@cmsvt.com>
14 * @copyright Copyright (c) 2021-2022 Sherwin Gaddis <sherwingaddis@gmail.com>
15 * @copyright Copyright (c) 2022 Stephen Waite <stephen.waite@cmsvt.com>
16 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
20 namespace OpenEMR\Services;
22 use OpenEMR\Common\Logging\SystemLogger;
23 use PhpOffice\PhpSpreadsheet\{
24 IOFactory,
25 Helper\Sample,
26 Spreadsheet,
29 class SpreadSheetService extends Spreadsheet
31 private array $arrayData;
32 private string $fileName;
33 private array $header;
34 private array $row;
35 private array $fields;
37 public function __construct(
38 $arrayData,
39 $fields,
40 $fileName = 'report'
41 ) {
42 if ((new Sample())->isCli()) {
43 (new SystemLogger())->error('This should only be run from a Web Browser' . PHP_EOL);
44 return;
46 parent::__construct();
48 $this->fileName = $fileName;
49 $this->arrayData = $arrayData;
50 $this->fields = $fields ?? [];
53 public function buildSpreadsheet()
56 if (empty($this->arrayData)) {
57 return false;
60 if (empty($this->fields)) {
61 $this->fields = array_keys($this->arrayData[0]);
64 $this->header = array_filter(array_keys($this->arrayData[0]), function ($v) {
65 if (in_array($v, $this->fields)) {
66 return csvEscape($v);
68 });
70 foreach ($this->arrayData as $item) {
71 $this->row[] = array_filter($item, function ($v, $k) {
72 if (in_array($k, $this->fields)) {
73 return csvEscape($v);
75 }, ARRAY_FILTER_USE_BOTH);
78 return true;
81 public function downloadSpreadsheet($format = 'Csv')
83 $sheet = $this->getActiveSheet();
84 $sheet->fromArray($this->header, null, 'A1');
85 $sheet->fromArray($this->row, null, 'A2');
86 header('Content-Description: File Transfer');
87 header('Content-Type: application/' . $format);
88 header('Content-Disposition: attachment; filename=' . basename($this->fileName . "." . $format));
89 header('Expires: 0');
90 header('Cache-Control: must-revalidate');
91 header('Pragma: public');
92 $writer = IOFactory::createWriter($this, $format);
93 $writer->save("php://output");