You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
2.3 KiB
80 lines
2.3 KiB
<?php
|
|
|
|
namespace app\admin\service;
|
|
|
|
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
|
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
|
|
|
class ExportService extends AdminBaseService
|
|
{
|
|
/**
|
|
* 导出 Excel
|
|
* @param array $data 二维数组(含表头)
|
|
* @param string $filename 导出文件名
|
|
*/
|
|
public static function exportExcel(array $data, string $filename = '')
|
|
{
|
|
if (empty($data)) {
|
|
throw new \Exception('导出数据不能为空');
|
|
}
|
|
|
|
$filename = $filename ?: '导出_' . date('Ymd_His') . '.xlsx';
|
|
|
|
$spreadsheet = new Spreadsheet();
|
|
$sheet = $spreadsheet->getActiveSheet();
|
|
|
|
// 列号转字母函数
|
|
$colIndexToLetter = function ($index) {
|
|
$letters = '';
|
|
while ($index >= 0) {
|
|
$letters = chr($index % 26 + 65) . $letters;
|
|
$index = intval($index / 26) - 1;
|
|
}
|
|
return $letters;
|
|
};
|
|
|
|
// 写入数据
|
|
foreach ($data as $rowIndex => $row) {
|
|
foreach ($row as $colIndex => $value) {
|
|
$cell = $colIndexToLetter($colIndex) . ($rowIndex + 1); // 例如 A1, B1...
|
|
$sheet->setCellValue($cell, $value);
|
|
}
|
|
}
|
|
|
|
// 输出到浏览器
|
|
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
|
header("Content-Disposition: attachment; filename=\"{$filename}\"");
|
|
header('Cache-Control: max-age=0');
|
|
|
|
$writer = new Xlsx($spreadsheet);
|
|
$writer->save('php://output');
|
|
exit;
|
|
}
|
|
|
|
/**
|
|
* 导出 CSV
|
|
* @param array $data 二维数组(含表头)
|
|
* @param string $filename 导出文件名
|
|
*/
|
|
public static function exportCsv(array $data, string $filename = '')
|
|
{
|
|
if (empty($data)) {
|
|
throw new \Exception('导出数据不能为空');
|
|
}
|
|
|
|
$filename = $filename ?: '导出_' . date('Ymd_His') . '.csv';
|
|
|
|
header('Content-Type: text/csv');
|
|
header("Content-Disposition: attachment; filename={$filename}");
|
|
|
|
$fp = fopen('php://output', 'w');
|
|
fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF)); // 防止中文乱码
|
|
|
|
foreach ($data as $row) {
|
|
fputcsv($fp, $row);
|
|
}
|
|
|
|
fclose($fp);
|
|
exit;
|
|
}
|
|
}
|
|
|