安装
> composer require phpoffice/phpspreadsheet
excel文件导出
调用方法
use app\exception\ApiException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\file\UploadedFile;
class Excel
{
public function exportExample()
{
$data = [
[
'time' => '时间',
'order_num' => '付款人数',
'did' => '付款订单数',
'total_price' => '付款金额',
'good_num' => '付款件数'
],
[
'time' => '时间',
'order_num' => '付款人数',
'did' => '付款订单数',
'total_price' => '付款金额',
'good_num' => '付款件数'
]
];
$xlsName = "测试" . date("YmdHis", time());
$head = ['日期', '付款人数', '付款订单数', '付款金额', '付款件数'];
$keys = ['time', 'order_num', 'did', 'total_price', 'good_num'];
$this->export($xlsName, $data, $head, $keys);
}
封装导出方法
public function export($name, $data = [], $head = [], $keys = [])
{
$count = count($head);
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
for ($i = 65; $i < $count + 65; $i++) {
$sheet->setCellValue(strtoupper(chr($i)) . '1', $head[$i - 65]);
}
foreach ($data as $key => $item) {
for ($i = 65; $i < $count + 65; $i++) {
$sheet->setCellValue(strtoupper(chr($i)) . ($key + 2), $item[$keys[$i - 65]]);
$spreadsheet->getActiveSheet()->getColumnDimension(strtoupper(chr($i)))->setWidth(20);
}
}
$names = $name;
$name = iconv('UTF-8', 'UCS-2BE', $name);
$len = strlen($name);
$str = '';
for ($i = 0; $i < $len - 1; $i = $i + 2) {
$c = $name[$i];
$c2 = $name[$i + 1];
if (ord($c) > 0) {
$str .= '\u' . base_convert(ord($c), 10, 16) . str_pad(base_convert(ord($c2), 10, 16), 2, 0, STR_PAD_LEFT);
} else {
$str .= '\u' . str_pad(base_convert(ord($c2), 10, 16), 4, 0, STR_PAD_LEFT);
}
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Data-Type: binary');
header('Data-Filename: ' . $str);
header('Content-Disposition: attachment;filename="' . $names . '.xlsx"');
header('Cache-Control: max-age=0');
header('Access-Control-Expose-Headers:Data-Type,Data-Filename');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
exit;
}
excel文件导入
将文件转为数据,方便后续对数组操作,插入数据库等
public function parseImportFileToArray(UploadedFile $file)
{
if ($file->getSize() > 5 * 1024 * 1024) {
@unlink($file->getRealPath());
throw new ApiException([400, '文件大小不能超过5M']);
}
if (!in_array($extension = $file->extension(), ['csv', 'xls', 'xlsx'])) {
@unlink($file->getRealPath());
throw new ApiException([400, '必须为excel表格,且必须为xls格式!']);
}
$type = strtolower($file->extension());
if ($type == 'xlsx') {
$types = 'Xlsx';
} elseif ($type == 'xls') {
$types = 'Xls';
} elseif ($type == 'csv') {
$types = 'Csv';
}
try {
$objReader = IOFactory::createReader($types);
$PHPExcel = $objReader->load($file->getRealPath());
$currentSheet = $PHPExcel->getSheet(0);
@unlink($file->getRealPath());
return $currentSheet->toArray('', true, true, true);
} catch (\Exception $exception) {
@unlink($file->getRealPath());
throw new ApiException([400, $exception->getMessage()]);
}
}
调用导入方法
public function importQuestion(Request $request)
{
$file = $request->file('file');
$excelArray = (new Excel)->parseImportFileToArray($file);
$data = array_slice($excelArray,2,count($excelArray) - 2,true);
$this->checkQuestionExcelData($data);
$this->questionMultipleAdd($data);
return $this->success([], '导入成功');
}