一部割愛していますが、下記のようなコードでPHPExcelを操作してエクセルファイルをダウンロードできています。直接の実行なら問題なく動くのですが、AjaxでPOSTしても動きません。ファイル作成まではできているのですが、ダウンロードができない状況です。
基本的なことがわからないのでコピペでやっていますが、おそらくヘッダーのところを吐き出すことで問題が起きているように思います。
POSTデータからSQLで値を取得しエクセルをダウンロードする必要があるのですが、どのようにすればいいかお分かりになる方、お力をお貸しください。
よろしくお願いいたします。
//---------------------------------------------------------------- //phpExcelの操作 //---------------------------------------------------------------- //PHPExcelの処理 require_once("../PHPExcel/Classes/PHPExcel.php"); require_once("../PHPExcel/Classes/PHPExcel/IOFactory.php"); $excel = new PHPExcel(); $excel->setActiveSheetIndex(0); $sheet = $excel->getActiveSheet(); $sheet->setTitle('住所録'); //---------------------------------------------- // Excel2007形式で出力する //---------------------------------------------- header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment;filename="sample.xlsx"'); header('Cache-Control: max-age=0'); $writer = PHPExcel_IOFactory::createWriter($excel, "Excel2007"); $writer->save("../address.xlsx"); $result=download_file('../address.xlsx'); //---------------------------------------------------------------- //ファイルをダウンロードする関数 //---------------------------------------------------------------- function download_file($path_file) { /* ファイルの存在確認 */ if (!file_exists($path_file)) { die("Error: File(".$path_file.") does not exist"); } /* オープンできるか確認 */ if (!($fp = fopen($path_file, "r"))) { die("Error: Cannot open the file(".$path_file.")"); } fclose($fp); /* ファイルサイズの確認 */ if (($content_length = filesize($path_file)) == 0) { die("Error: File size is 0.(".$path_file.")"); } /* ダウンロード用のHTTPヘッダ送信 */ header("Content-Disposition: inline; filename=\"".basename($path_file)."\""); header("Content-Length: ".$content_length); header("Content-Type: application/octet-stream"); /* ファイルを読んで出力 */ ob_end_clean();// ファイルの内容を出力する前に入力バッファの中身をクリアする if (!readfile($path_file)) { die("Cannot read the file(".$path_file.")"); } }
Ajax
<script> $(function(){ $("#form").submit(function(){ //選択されたチェックボックスの値を配列に保存 var checks=[]; $("[name='check[]']:checked").each(function(){ checks.push(this.value); }); $.ajax({ type: "POST", url: "form.php", data: { "checks":checks }, success: function(data){ alert(data); } }); return false; //submitイベントハンドラにfalseを返し,action処理をキャンセル }); }); </script>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/04/15 10:07
2018/04/15 10:28 編集