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.
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\
{
29 class SpreadSheetService
extends Spreadsheet
31 private array $arrayData;
32 private string $fileName;
33 private array $header;
35 private array $fields;
37 public function __construct(
42 if ((new Sample())->isCli()) {
43 (new SystemLogger())->error('This should only be run from a Web Browser' . PHP_EOL
);
46 parent
::__construct();
48 $this->fileName
= $fileName;
49 $this->arrayData
= $arrayData;
50 $this->fields
= $fields ??
[];
53 public function buildSpreadsheet()
56 if (empty($this->arrayData
)) {
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
)) {
70 foreach ($this->arrayData
as $item) {
71 $this->row
[] = array_filter($item, function ($v, $k) {
72 if (in_array($k, $this->fields
)) {
75 }, ARRAY_FILTER_USE_BOTH
);
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));
90 header('Cache-Control: must-revalidate');
91 header('Pragma: public');
92 $writer = IOFactory
::createWriter($this, $format);
93 $writer->save("php://output");