Skip to content

Commit

Permalink
test: 导出改为xlsx
Browse files Browse the repository at this point in the history
  • Loading branch information
twinh committed Jan 4, 2019
1 parent 914c714 commit dd3d6f6
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/Service/Excel.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@
use ErrorException;
use Miaoxing\Plugin\BaseService;
use PHPExcel_IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Wei\Logger;
use Wei\Response;
use Wei\RetTrait;

/**
* @property Logger logger
* @property Response response
*/
class Excel extends BaseService
{
Expand Down Expand Up @@ -66,4 +72,36 @@ protected function removeNullRow($data)
}
return $data;
}

public function export($fileName, $data)
{
$res = $this->response;
$res->setHeader([
'Content-type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Content-Disposition' => 'attachment;filename=' . $fileName . '.xlsx',
]);
$res->sendHeader();

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$startRow = '1';
$startColumn = 'A';

foreach ($data as $rowData) {
$currentColumn = $startColumn;
foreach ($rowData as $cellValue) {
// 大于15位数字开始变0 12位空间不足变科学计数法
if (is_numeric($cellValue) && strlen($cellValue) >= 12) {
$sheet->setCellValueExplicit($currentColumn . $startRow, $cellValue, DataType::TYPE_STRING);
} else {
$sheet->setCellValue($currentColumn . $startRow, $cellValue);
}
++$currentColumn;
}
++$startRow;
}

$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
}
}

0 comments on commit dd3d6f6

Please sign in to comment.