How to create an excel file with php?

22 January 2023 568 Reading time: 59 second

You can use the PHPSpreadsheet library to create files in Excel format with PHP. The sample code is as follows:

<?php
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

// Verileri dizi olarak tanımlayın
$data = array(
    array("Ad" => "John", "Soyad" => "Doe", "Yaş" => 25),
    array("Ad" => "Jane", "Soyad" => "Doe", "Yaş" => 24),
    array("Ad" => "Bob", "Soyad" => "Smith", "Yaş" => 27),
);

// Dizi verilerini hücrelere yazın
$row = 1;
foreach ($data as $item) {
    $col = 0;
    foreach ($item as $key => $value) {
        $sheet->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}

// Dosyayı oluşturun ve indirin
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="veriler.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');

This code creates an array containing the data and writes the array data to the cells, then downloads the resulting file.
You can get information about the phpSpreadsheet library here: PhpSpreadsheet

Similar articles