Postingan lainnya
export mysql to csv php
mohon bantuannya contoh sederhana script php untuk export database mysql to csv
1 Jawaban:
Saya pake PHPExcel (sudah deprecated, yg terbaru PHPSpreadsheet). Ini cuma contoh. Silahkan sesuaikan dengan kebutuhan anda
Download <a href='https://codeload.github.com/PHPOffice/PHPExcel/zip/1.8.1 '>https://codeload.github.com/PHPOffice/PHPExcel/zip/1.8.1 </a> extract ke htdocs rename PHPExcel-1.81 jadi PHPExcel.
Lalu di htdocs buat file testcsv.php yg isinya seperti di bawah ini (sesuaikan table/database anda)
sudah tes running di php 5.5 & 7.0
<pre> <?php /** Include PHPExcel */ require_once dirname(FILE) . '/PHPExcel/Classes/PHPExcel.php';
//Read database -- disini table alamat (id, nama, alamat) $con = mysqli_connect("localhost","root","","test"); $result = mysqli_query($con,"SELECT * FROM alamat"); $Data=mysqli_fetch_all($result,MYSQLI_ASSOC); $Title = "My Report";
// Create new PHPExcel object $objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("Tobing") ->setLastModifiedBy("Tobing") ->setTitle($Title) ->setSubject($Title) ->setDescription($Title) ->setKeywords("office PHPExcel php") ->setCategory("CSV REPORT");
$objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A1', 'Date') ->setCellValue('B1', date("d-m-Y"));
// Report Header $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A3', '') ->setCellValue('B3', $Title) ->setCellValue('C3', '');
// Table Header $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A5', 'ID') ->setCellValue('B5', 'Nama') ->setCellValue('C5', 'Alamat');
$xRow = 6;
foreach ($Data as $row)
{
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$xRow, $row['id'])
->setCellValue('B'.$xRow, $row['nama'])
->setCellValue('C'.$xRow, $row['alamat']);
$xRow ++;
}
header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="'.$Title.'.csv"'); header('Cache-Control: max-age=0'); $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); exit;
?>
</pre>