COM接口來實現php批量替換Exclphp
$excelPath = "e:\\excel"; $total = $success = $jump = 0; $objExcel = new COM("excel.application") or die("不能打開Excel應用程序"); $handle = opendir($excelPath); //打開當前目錄 readdir($handle); //排除"." readdir($handle); //排除 ".." //循環讀取文件 while ($file = readdir($handle)) { $total++; //生成源文件名 $fileName = $excelPath . DIRECTORY_SEPARATOR .$file; $pathinfo = pathinfo($fileName); if(strtolower($pathinfo['extension']) != 'xls'){ echo "已跳過:".$file.",文件格式不對"; $jump++; continue; } echo "正在替換文件:".$file."\n"; if(file_exists($fileName)){ if(!$objExcel->Application->WorkBooks->Open($fileName)){ echo $file."打開失敗,跳過!"; $jump++; continue; } } else{ echo $fileName."文件不存在\n"; $jump++; continue; } $totalRow = $objExcel->ActiveSheet->UsedRange->Rows->Count; for($i=1;$i<=$totalRow;$i++){ $keyword = trim($objExcel->Worksheets(1)->Range("A".$i)->Value);//獲取到值 if(in_array($keyword,$replaceIn)){//判斷後在這裏進行替換 $objExcel->Worksheets(1)->Range("B".$i)->Value = $replaceRule[$keyword]; $objExcel->Worksheets(1)->Range("B".$i)->Font->Name = "黑體"; $objExcel->Worksheets(1)->Range("B".$i)->Font->Size = 12; } } if(!$objExcel->ActiveWorkBook->Saved) { $objExcel->ActiveWorkBook->save(); echo $file."保存成功!\n"; $success++; } //關閉工做簿 $objExcel->Quit(); } echo "\n所有替換完成!共{$total}個,成功{$success}個,跳過{$jump}個!\n"; //清空對象 $objExcel = null; exit;
須要注意的是,儘可能把這個程序放在命令行下跑,別放在IIS或APACHE下面,由於是調用的系統組件COM,因此可能會出現各類奇葩的錯誤,這些錯誤的緣由都是由於權限不足引發的,因此直接用管理員身份運行命令行,在命令行下跑就能把權限問題排除在外!app