php-fakerHow can I generate fake data in XLSX format using PHP Faker?
Using the PHP Faker library, you can generate fake data in XLSX format. Here is an example code block that will generate a XLSX spreadsheet with 10 rows of fake data:
<?php
require_once 'vendor/fzaninotto/faker/src/autoload.php';
$faker = Faker\Factory::create();
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
for ($i = 0; $i < 10; $i++) {
$sheet->setCellValue('A' . ($i + 1), $faker->name);
$sheet->setCellValue('B' . ($i + 1), $faker->address);
$sheet->setCellValue('C' . ($i + 1), $faker->phoneNumber);
$sheet->setCellValue('D' . ($i + 1), $faker->email);
}
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save('fake_data.xlsx');
This code:
- Requires the Faker library with
require_once 'vendor/fzaninotto/faker/src/autoload.php';
- Creates an instance of Faker with
$faker = Faker\Factory::create();
- Creates a new Spreadsheet object with
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
- Creates a new Sheet object from the Spreadsheet with
$sheet = $spreadsheet->getActiveSheet();
- Loops 10 times to generate fake data with
for ($i = 0; $i < 10; $i++) {...}
- Sets the cell values of the Sheet object with
$sheet->setCellValue('A' . ($i + 1), $faker->name);
- Creates a new XLSX writer object with
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
- Saves the Spreadsheet object to a file with
$writer->save('fake_data.xlsx');
This will generate a XLSX spreadsheet file called fake_data.xlsx
that contains 10 rows of fake data.
Helpful links
More of Php Faker
- How do I generate a zip file using PHP Faker?
- How do I generate a fake year in Laravel using Faker?
- How do I generate a valid VAT number using Laravel Faker?
- How can I generate fake values using Laravel Faker?
- How do I generate a random digit using PHP Faker?
- How can I generate unique data with Laravel Faker?
- How do I check which version of Laravel Faker I am using?
- How do I use the Laravel Faker numerify function?
- How can I use Faker with Laravel?
See more codes...