先說一下, 玩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() }}