今天要處理兩個excel。兩個循環嵌套驗證重復性。所以寫了幾個函數來處理20億次的數據量。
一。把excel讀出來,保存為json。利用phpexcel插件:
<?php header("Content-Type:text/html;charset=utf-8"); $dir=dirname(__FILE__);//找到當前腳本所在路徑 require $dir."/PHPExcel/PHPExcel/IOFactory.php";//引入讀取excel的類文件 $filename=$dir."/o.xls"; $fileType=PHPExcel_IOFactory::identify($filename);//自動獲取文件的類型提供給phpexcel用 $objReader=PHPExcel_IOFactory::createReader($fileType);//獲取文件讀取操作對象 $sheetName=array("Sheet1"); $objReader->setLoadSheetsOnly($sheetName);//只加載指定的sheet $objPHPExcel=$objReader->load($filename);//加載文件 /**$sheetCount=$objPHPExcel->getSheetCount();//獲取excel文件里有多少個sheet for($i=0;$i<$sheetCount;$i++){ $data=$objPHPExcel->getSheet($i)->toArray();//讀取每個sheet里的數據 全部放入到數組中 print_r($data); }**/ $i=0; foreach($objPHPExcel->getWorksheetIterator() as $sheet){//循環取sheet foreach($sheet->getRowIterator() as $row){//逐行處理 if($row->getRowIndex()<2){ continue; } $da = array(); foreach($row->getCellIterator() as $cell){//逐列讀取 $data=$cell->getValue();//獲取單元格數據 $da[] = $data; } $d[] = $da; } } $dd =json_encode($d); touch('o.html'); file_put_contents('o.html', $dd); echo "成功";
二、把弄好的數組,在保存為execl。但是直接操作excel,會比較慢,所保存為csv
:
<?php $filenamew ="dd.html";//讀取出來的json $json_sw = file_get_contents($filenamew); $data = json_decode($json_sw); $filename = "33"; //保存的文件名 header("Content-type: text/csv"); header("Content-Disposition: attachment; filename={$filename}.csv"); header("Pragma: no-cache"); header("Expires: 0"); outputCSV($data); function outputCSV($data) { $outputBuffer = fopen("php://output", 'w'); foreach($data as $val) { foreach ($val as $key => $val2) { $val[$key] = iconv('utf-8', 'gbk', $val2);// CSV的Excel支持GBK編碼,一定要轉換,否則亂碼 } fputcsv($outputBuffer, $val); } fclose($outputBuffer); } ?>
