1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <?php
- namespace Tool\ShanTaoTool\Excel;
- use PhpOffice\PhpSpreadsheet\IOFactory;
- use PhpOffice\PhpSpreadsheet\Spreadsheet;
- class Export
- {
- /**
- * params $headerList 头部列表信息(一维数组) 必传
- * params $data 导出的数据(二维数组) 必传
- * params $filename 文件名称转码 必传
- * PS:出现数字格式化情况,可添加看不见的符号,使其正常,如:"\t"
- **/
- public function exportToCsv($headerList = [] , $data = [] , $fileName = ''){
- //文件名称转码
- // $fileName = iconv('UTF-8', 'GBK', $fileName);
- //设置header头
- header('Content-Type: application/vnd.ms-excel');
- header('Content-Disposition: attachment;filename=' . $fileName . '.csv');
- header('Cache-Control: max-age=0');
- //打开PHP文件句柄,php://output,表示直接输出到浏览器
- $fp = fopen("php://output","a");
- fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF)); // 添加 BOM
- //输出Excel列表名称信息
- foreach ($headerList as $key => $value) {
- // $headerList[$key] = iconv('UTF-8', 'GBK', $value);//CSV的EXCEL支持BGK编码,一定要转换,否则乱码
- $headerList[$key] = $value;//CSV的EXCEL支持BGK编码,一定要转换,否则乱码
- }
- //使用fputcsv将数据写入文件句柄
- fputcsv($fp, $headerList);
- //计数器
- $num = 0;
- //每隔$limit行,刷新一下输出buffer,不要太大亦不要太小
- $limit = 100000;
- //逐行去除数据,不浪费内存
- $count = count($data);
- for($i = 0 ; $i < $count ; $i++){
- $num++;
- //刷新一下输出buffer,防止由于数据过多造成问题
- if($limit == $num){
- ob_flush();
- flush();
- $num = 0;
- }
- $row = $data[$i];
- foreach ($row as $key => $value) {
- $value = is_numeric($value) ? $value."\t" : $value;//解决输出长度较长的数字型变成科学计数法
- $row[$key] = $value;
- // $row[$key] = iconv('UTF-8', 'GBK', $value);
- }
- fputcsv($fp, $row);
- }
- }
- public function exportToExcel($headerList = [] , $datas = [] , $fileName = '')
- {
- $filename = $fileName.'.xlsx';
- header('Content-Type: application/vnd.ms-excel');
- header('Content-Disposition: attachment;filename="'.$filename.'"');
- header('Cache-Control: max-age=0');
- $spreadsheet = new Spreadsheet();
- $worksheet = $spreadsheet->getActiveSheet();
- $worksheet->setTitle($fileName);
- foreach ($headerList as $key=>$header){
- //设置标题
- $worksheet->setCellValueByColumnAndRow((int)$key+1, 1, $header);
- }
- foreach ($datas as $kk=>$data){
- $tmp = 0;
- foreach ($data as $k=>$val){
- //设置数据
- $worksheet->setCellValueByColumnAndRow((int)$tmp+1,(int)$kk+2,$val);
- $tmp++;
- }
- }
- $writer =IOFactory::createWriter($spreadsheet, 'Xlsx');
- $writer->save('php://output');
- }
- public function importExcel($file)
- {
- $reader = IOFactory::createReader('Xlsx');
- //打开文件、载入excel表格
- $spreadsheet = $reader->load($file);
- # 获取活动工作薄
- return $spreadsheet->getActiveSheet()->toArray();
- }
- }
|