先说一下, 玩php的导入和导出, 不要考虑搞什么带格式的.excel文件, 老老实实地搞csv, 满足你大数据量的需求。重点是减轻你的工作负担。先上源代码。本文只上干净代码, 不搞第三方库。
php导出csv文件代码
/** * 导出csv * @param $data * @return void */ public static function exportCsv($data,$filename='') { header("Content-type: text/csv;charset=UTF-8"); header("Content-Disposition: attachment;filename=" .urlencode($filename. time()).'.csv'); header('Cache-Control: must-revalidate,post-check=0,pre-check=0'); header('Expires: 0'); header('Pragma: public'); header('Access-Control-Allow-Origin: *'); header('Access-Control-Expose-Headers: Content-Disposition'); ob_end_clean(); ob_start(); //内存中打开,不占用硬盘 $fp = fopen('php'.'://output','w'); //'php'.'://output';直接写简书不让保存,只能换这种切开链接的方式写 fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF)); //每1000条刷新一次缓存 foreach ($data as $key=>$value) { if ($key % 1000 ==0) { ob_flush(); flush(); } //添加空格数字变文本 foreach($value as $k=>$v){ $value[$k] = "\t".$v; } fputcsv($fp, $value); } fclose($fp); ob_flush(); flush(); ob_end_clean(); exit; }}
上述伪代码接着改一改, 再放到生产环境下。
导入csv文件代码
$fp = fopen($filePath, 'rb'); $data = []; while (!feof($fp)) { $temp = fgetcsv($fp); if (empty($temp)) { // 空数据直接丢弃 continue; } $data[] = $temp; } fclose($fp); unlink($filePath);
建议在生产环境下, 之后产生的$data你验证一轮之后再去循环插进数据库。
使用vue弹出下载效果
export function exportDownloadFile(res){ // 文件名,获取原始的文件名 const fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]) const data = res.data // Blob数据对象 const uA = window.navigator.userAgent const isIE = /msie\s|trident\/|edge\//i.test(uA) && !!('uniqueID' in document || 'documentMode' in document || 'ActiveXObject' in window || 'MSInputMethodContext' in window) let url = window.URL.createObjectURL(new Blob([data])) let link = document.createElement('a') link.style.display = 'none' link.href = url link.setAttribute('download', fileName) document.body.appendChild(link) // 兼容IE if (isIE) { navigator.msSaveBlob(new Blob([data]), fileName) } else { link.click() }}