Kode Ekspor PHP Excel (Data ke File)

oleh Vincy. Terakhir diubah pada 23 September 2022.

Ekspor data ke file excel terutama digunakan untuk mengambil cadangan. Saat mengambil cadangan basis data, format excel adalah format yang nyaman untuk dibaca dan dikelola dengan mudah. Untuk beberapa aplikasi yang mengekspor data, penting untuk mengambil cadangan atau salinan offline dari database server.

Artikel ini menunjukkan cara mengekspor data ke excel menggunakan PHP. Ada banyak cara untuk mengimplementasikan fungsi ini. Kita telah melihat contoh ekspor data dari MySQL.

Artikel ini menggunakan library PHPSpreadSheet untuk mengimplementasikan ekspor PHP excel.

Ini adalah perpustakaan populer yang mendukung membaca, dan menulis file excel. Ini akan memperlancar operasi ekspor-impor excel melalui fungsi bawaannya.

Contoh lengkap dalam artikel ini akan memungkinkan Anda membuat alat ekspor atau aplikasi Anda sendiri.
ekspor php excel

Tentang Contoh ini

Ini akan menampilkan antarmuka minimal dengan daftar catatan database dan tombol “Ekspor ke Excel”. Dengan mengklik tombol ini, ia akan memanggil ExportService khusus yang dibuat untuk contoh ini.

Layanan ini membuat instance class library PHPSpreadsheet dan menetapkan header kolom dan nilai. Kemudian ia membuat objek penulis dengan mengatur instance PHPSpreadsheet untuk menampilkan data ke excel.

Ikuti langkah-langkah di bawah ini untuk membiarkan contoh ini berjalan di lingkungan Anda.

  1. Buat dan atur database dengan data yang diekspor ke excel.
  2. Unduh kode di akhir artikel ini dan konfigurasikan database.
  3. Tambahkan perpustakaan PHPSpreadSheet dan dependensi lainnya ke dalam aplikasi.

Kami telah menggunakan perpustakaan PHPSpreadsheet untuk menyimpan URL gambar yang diekstraksi.

1) Buat dan atur database dengan data yang diekspor ke excel

Buat database bernama “db_excel_export” dan impor skrip SQL di bawah ini ke dalamnya.

struktur.sql

--
-- Table structure for table `tbl_products`
--

CREATE TABLE `tbl_products` (
  `id` int(8) NOT NULL,
  `name` varchar(255) NOT NULL,
  `price` double(10,2) NOT NULL,
  `category` varchar(255) NOT NULL,
  `product_image` text NOT NULL,
  `average_rating` float(3,1) NOT NULL
);

--
-- Dumping data for table `tbl_products`
--

INSERT INTO `tbl_products` (`id`, `name`, `price`, `category`, `product_image`, `average_rating`) VALUES
(1, 'Tiny Handbags', 100.00, 'Fashion', 'gallery/handbag.jpeg', 5.0),
(2, 'Men's Watch', 300.00, 'Generic', 'gallery/watch.jpeg', 4.0),
(3, 'Trendy Watch', 550.00, 'Generic', 'gallery/trendy-watch.jpeg', 4.0),
(4, 'Travel Bag', 820.00, 'Travel', 'gallery/travel-bag.jpeg', 5.0),
(5, 'Plastic Ducklings', 200.00, 'Toys', 'gallery/ducklings.jpeg', 4.0),
(6, 'Wooden Dolls', 290.00, 'Toys', 'gallery/wooden-dolls.jpeg', 5.0),
(7, 'Advanced Camera', 600.00, 'Gadget', 'gallery/camera.jpeg', 4.0),
(8, 'Jewel Box', 180.00, 'Fashion', 'gallery/jewel-box.jpeg', 5.0),
(9, 'Perl Jewellery', 940.00, 'Fashion', 'gallery/perls.jpeg', 5.0);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_products`
--
ALTER TABLE `tbl_products`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_products`
--
ALTER TABLE `tbl_products`
  MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;

2) Unduh kode dan konfigurasikan database

Kode sumber berisi file-file berikut. Bagian ini menjelaskan konfigurasi database.

struktur file ekspor excel

Setelah Anda mengunduh kode ekspor excel dari halaman ini, Anda dapat menemukan DataSource.php file di lib map. Buka dan konfigurasikan detail database di dalamnya seperti di bawah ini.

<?php 
class DataSource
{

    const HOST = 'localhost';

    const USERNAME = 'root';

    const PASSWORD = '';

    const DATABASENAME = 'db_excel_export';

    ...
    ...
?>

3) Tambahkan perpustakaan PHPSpreadSheet dan dependensi lainnya ke dalam aplikasi

Ketika Anda melihat dokumentasi PHPSpreadsheet, ini menyediakan langkah-langkah instalasi yang mudah diikuti.

Ini memberikan perintah komposer untuk menambahkan PHPSpreadsheet dan dependensi terkait ke dalam aplikasi.

composer require phpoffice/phpspreadsheet

Untuk PHP versi 7

Tambahkan spesifikasi di bawah ini ke file composer.json.

{
    "require": {
        "phpoffice/phpspreadsheet": "^1.23"
    },
    "config": {
        "platform": {
            "php": "7.3"
        }
    }
}

lalu lari

composer update

Catatan: PHPSpreadsheet membutuhkan setidaknya versi PHP 7.3.

Bagaimana itu bekerja

Antarmuka sederhana dengan opsi ekspor

Halaman ini mengambil data dari database MySQL dan menampilkannya dalam bentuk grid. Di bawah kisi data, halaman ini menampilkan tombol “Ekspor Excel”.

Dengan mengklik tombol ini, parameter tindakan dikirim ke URL untuk memanggil layanan ekspor excel di PHP.

index.php

<?php
require_once __DIR__ . '/lib/Post.php';
$post = new post();
$postResult = $post->getAllPost();
$columnResult = $post->getColumnName();
if (! empty($_GET["action"])) {
    require_once __DIR__ . '/lib/ExportService.php';
    $exportService = new ExportService();
    $result = $exportService->exportExcel($postResult, $columnResult);
}
?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://phppot.com/php/php-excel-export/./style.css" type="text/css" rel="stylesheet" />
</head>
<body>
    <div id="table-container">
        <table id="tab">
            <thead>
                <tr>
                    <th width="5%">Id</th>
                    <th width="35%">Name</th>
                    <th width="20%">Price</th>
                    <th width="25%">Category</th>
                    <th width="25%">product Image</th>
                    <th width="20%">Average Rating</th>
                </tr>
            </thead>
            <tbody>
            <?php
            if (! empty($postResult)) {
                foreach ($postResult as $key => $value) {
                    ?>
                <tr>
                    <td><?php echo $postResult[$key]["id"]; ?></td>
                    <td><?php echo $postResult[$key]["name"]; ?></td>
                    <td><?php echo $postResult[$key]["price"]; ?></td>
                    <td><?php echo $postResult[$key]["category"]; ?></td>
                    <td><?php echo $postResult[$key]["product_image"]; ?></td>
                    <td><?php echo $postResult[$key]["average_rating"]; ?></td>
                </tr>
            <?php
                }
            }
            ?>
            </tbody>
        </table>
        <div class="btn">
            <form action="" method="POST">
                <a
                    href="<?php echo strtok($_SERVER["REQUEST_URI"]);?><?php echo $_SERVER["QUERY_STRING"];?>?action=export"><button
                        type="button" id="btnExport" name="Export"
                        value="Export to Excel" class="btn btn-info">Export
                        to Excel</button></a>
            </form>
        </div>
    </div>
</body>
</html>

Panggilan model PHP menyiapkan kueri untuk mengambil data untuk diekspor

Ini adalah kelas model PHP yang dipanggil untuk membaca data dari database. Array data akan dikirim ke layanan ekspor untuk membangun objek lembar excel.

Itu getColumnName() membaca array nama kolom tabel database. Array ini akan memasok data untuk membentuk baris pertama di excel untuk membuat header kolom.

Itu dapatkanSemuaPost() membaca baris data yang akan diulang dan mengatur sel data dengan nilai.

lib/Post.php

<?php
class Post
{

    private $ds;

    public function __construct()
    {
        require_once __DIR__ . '/DataSource.php';
        $this->ds = new DataSource();
    }

    public function getAllPost()
    {
        $query = "select * from tbl_products";
        $result = $this->ds->select($query);
        return $result;
    }

    public function getColumnName()
    {
        $query = "select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=N'tbl_products'";
        $result = $this->ds->select($query);
        return $result;
    }
}
?>

Layanan ekspor PHP excel

Layanan ini membantu mengekspor data ke lembar excel. File yang dihasilkan akan diunduh ke browser dengan mengatur properti PHP header().

$postResult memiliki data baris dan $columnResult memiliki data kolom.

Contoh ini membuat instance class library PHPSpreadSheet dan menyetel header kolom dan nilai. Kemudian ia membuat objek penulis dengan mengatur instance spreadsheet untuk menampilkan data ke excel.

lib/ExportService.php

<?php
use PhpOfficePhpSpreadsheetIOFactory;
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;
use PhpOfficePhpSpreadsheetCalculationTextDataReplace;
require_once __DIR__ . '/../vendor/autoload.php';

class ExportService
{

    public function exportExcel($postResult, $columnResult)
    {
        $spreadsheet = new Spreadsheet();
        $spreadsheet->getProperties()->setTitle("excelsheet");
        $spreadsheet->setActiveSheetIndex(0);
        $spreadsheet->getActiveSheet()->SetCellValue('A1', ucwords($columnResult[0]["COLUMN_NAME"]));
        $spreadsheet->getActiveSheet()->SetCellValue('B1', ucwords($columnResult[1]["COLUMN_NAME"]));
        $spreadsheet->getActiveSheet()->SetCellValue('C1', ucwords($columnResult[2]["COLUMN_NAME"]));
        $spreadsheet->getActiveSheet()->SetCellValue('D1', ucwords($columnResult[3]["COLUMN_NAME"]));
        $spreadsheet->getActiveSheet()->SetCellValue('E1', str_replace('_', ' ', ucwords($columnResult[4]["COLUMN_NAME"], '_')));
        $spreadsheet->getActiveSheet()->SetCellValue('F1', str_replace('_', ' ', ucwords($columnResult[5]["COLUMN_NAME"], '_')));
        $spreadsheet->getActiveSheet()
            ->getStyle("A1:F1")
            ->getFont()
            ->setBold(true);
        $rowCount = 2;
        if (! empty($postResult)) {
            foreach ($postResult as $k => $v) {
                $spreadsheet->getActiveSheet()->setCellValue("A" . $rowCount, $postResult[$k]["id"]);
                $spreadsheet->getActiveSheet()->setCellValue("B" . $rowCount, $postResult[$k]["name"]);
                $spreadsheet->getActiveSheet()->setCellValue("C" . $rowCount, $postResult[$k]["price"]);
                $spreadsheet->getActiveSheet()->setCellValue("D" . $rowCount, $postResult[$k]["category"]);
                $spreadsheet->getActiveSheet()->setCellValue("E" . $rowCount, $postResult[$k]["product_image"]);
                $spreadsheet->getActiveSheet()->setCellValue("F" . $rowCount, $postResult[$k]["average_rating"]);
                $rowCount ++;
            }
            $spreadsheet->getActiveSheet()
                ->getStyle('A:F')
                ->getAlignment()
                ->setWrapText(true);

            $spreadsheet->getActiveSheet()
                ->getRowDimension($rowCount)
                ->setRowHeight(- 1);
        }
        $writer = IOFactory::createWriter($spreadsheet, 'Xls');
        header('Content-Type: text/xls');
        $fileName="exported_excel_" . time() . '.xls';
        $headerContent="Content-Disposition: attachment;filename="" . $fileName . '"';
        header($headerContent);
        $writer->save('php://output');
    }
}
?>

Unduh

Kembali ke Atas


Source link