From 0ba561eb962f177793958c6c8478985d4bb5dde4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erodis=20P=C3=A9rez=20Michel?= Date: Thu, 21 Oct 2021 14:46:34 -0400 Subject: [PATCH] Update Helper.php Add support to get file content as base64 string to render in json object. --- src/phpSpreadsheet/Helper.php | 46 +++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/phpSpreadsheet/Helper.php b/src/phpSpreadsheet/Helper.php index cf7163e..0ee1941 100644 --- a/src/phpSpreadsheet/Helper.php +++ b/src/phpSpreadsheet/Helper.php @@ -525,6 +525,41 @@ public static function save($filename='excel', $format='Xlsx') $objWriter->save($filepath); return $filepath; } + + /** + * Output file content to base64 uri string + * @param string $format + * @return string + * + * @throws \Exception + */ + public static function getFileContent($format = 'Xlsx') + { + self::cleanOutput(); + + $objPhpSpreadsheet = self::validExcelObj(); + + // Create Writer first + $objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPhpSpreadsheet, $format); + $objWriter->setPreCalculateFormulas(true); + + /** + * Type Mapping + */ + $inTypeList = isset(self::$_writerTypeInfo[$format]); + $contentType = ($inTypeList) ? self::$_writerTypeInfo[$format]['contentType'] : ''; + + ob_start(); + // Save file + $objWriter->save('php://output'); + $content = ob_get_contents(); + ob_clean(); + + $base64FileContent = base64_encode($content); + + return "data:{$contentType};base64,{$base64FileContent}"; + } + /** * Get data of a row from the actived sheet of PhpSpreadsheet @@ -863,4 +898,15 @@ private static function validSheetObj($sheetObj=NULL) throw new Exception("Invalid or empty PhpSpreadsheet Sheet Object", 400); } } + + /** + * This function discards the contents of the top most output buffer + * and turns off this output buffering. + */ + private static function cleanOutput() + { + for ($level = ob_get_level(); $level > 0; --$level) { + @ob_end_clean(); + } + } }