--- /dev/null
+<?php
+
+namespace Cubist\Excel;
+
+use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use PhpOffice\PhpSpreadsheet\Style\Alignment;
+use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
+use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
+
+class Excel
+{
+ /**
+ * @param $sheetname string
+ * @param $datas array
+ * @param $head array|null
+ * @param $output string|null
+ * @param $width int|null
+ * @return Spreadsheet
+ * @throws \PhpOffice\PhpSpreadsheet\Exception
+ */
+ public static function fromArray($sheetname, $datas, $head = null, $output = null, $width = null)
+ {
+ $columns = 0;
+
+ $excel = new Spreadsheet();
+ $excel->getDefaultStyle()
+ ->getNumberFormat()
+ ->setFormatCode(
+ NumberFormat::FORMAT_TEXT
+ );
+ $sheet = $excel->getActiveSheet();
+ $sheet->setTitle($sheetname);
+
+ $line = 1;
+ if (!is_null($head)) {
+ $c = 0;
+ foreach ($head as $label) {
+ $columns = max($columns, $c);
+ $cell = $sheet->getCellByColumnAndRow($c, $line);
+ $cell->setValue($label);
+ $style = $sheet->getStyleByColumnAndRow($c, $line);
+ $style->getFont()->setBold(true);
+ $style->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
+
+ $c++;
+ }
+ $line++;
+ }
+
+ foreach ($datas as $l) {
+ $c = 0;
+ foreach ($l as $v) {
+ $columns = max($columns, $c);
+ $sheet->getCellByColumnAndRow($c, $line)->setValue($v);
+ $style = $sheet->getStyleByColumnAndRow($c, $line);
+ $style->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
+ $style->getAlignment()->setWrapText(true);
+ $c++;
+ }
+ $line++;
+ }
+
+ for ($i = 0; $i <= $columns; $i++) {
+ if (null === $width || !isset($width[$i]) || null === $width[$i] || $width[$i] == 'auto') {
+ $sheet->getColumnDimensionByColumn($i)->setAutoSize(true);
+ } else {
+ $sheet->getColumnDimensionByColumn($i)->setAutoSize(false)->setWidth($width[$i]);
+ }
+ }
+
+ if (null !== $output) {
+ self::_save($excel, $output);
+ }
+
+ return $excel;
+ }
+
+ protected static function _save($excel, $output)
+ {
+ $writer = new Xlsx();
+ $writer->setSpreadsheet($excel);
+ $writer->save($output);
+ }
+}
\ No newline at end of file