export mysql to csv php

mohon bantuannya contoh sederhana script php untuk export database mysql to csv

avatar cadis
@cadis

8 Kontribusi 0 Poin

Diperbarui 5 tahun yang lalu

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> &lt;?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-&gt;getProperties()-&gt;setCreator("Tobing") -&gt;setLastModifiedBy("Tobing") -&gt;setTitle($Title) -&gt;setSubject($Title) -&gt;setDescription($Title) -&gt;setKeywords("office PHPExcel php") -&gt;setCategory("CSV REPORT");

$objPHPExcel-&gt;setActiveSheetIndex(0) -&gt;setCellValue('A1', 'Date') -&gt;setCellValue('B1', date("d-m-Y"));

// Report Header $objPHPExcel-&gt;setActiveSheetIndex(0) -&gt;setCellValue('A3', '') -&gt;setCellValue('B3', $Title) -&gt;setCellValue('C3', '');

// Table Header $objPHPExcel-&gt;setActiveSheetIndex(0) -&gt;setCellValue('A5', 'ID') -&gt;setCellValue('B5', 'Nama') -&gt;setCellValue('C5', 'Alamat');

$xRow = 6;
foreach ($Data as $row) {
$objPHPExcel-&gt;setActiveSheetIndex(0) -&gt;setCellValue('A'.$xRow, $row['id']) -&gt;setCellValue('B'.$xRow, $row['nama']) -&gt;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-&gt;save('php://output'); exit;

?&gt;

</pre>

avatar mltobing
@mltobing

114 Kontribusi 77 Poin

Dipost 5 tahun yang lalu

Login untuk ikut Jawaban