Creating an Excel file in PHP is a common task for many web applications. There are several libraries available that make it easier to create and manage Excel files in PHP. One of the most popular libraries is PHPExcel.
Php code
To use PHPExcel, you need to download the library from its website and include it in your project. Here's how to create a basic Excel file using PHPExcel:
Include the library in your PHP file:
require_once 'PHPExcel.php';
Create an instance of the PHPExcel class:
$excel = new PHPExcel();
Get the active worksheet:
$sheet = $excel->getActiveSheet();
Set cell values:
$sheet->setCellValue('A1', 'Name');
$sheet->setCellValue('B1', 'Age');
$sheet->setCellValue('A2', 'John Doe');
$sheet->setCellValue('B2', '30');
Here, we are setting values for cells A1 and B1 to "Name" and "Age", respectively. And for cells A2 and B2, we are setting values to "John Doe" and "30".
Save the file as an Excel file:
$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel2017');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="sample.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
In this step, we are using the createWriter method of the PHPExcel_IOFactory class to create a writer object. This writer object is then used to save the file as an Excel file.
We are also setting headers to make sure the file is downloaded and not displayed in the browser. The content type header is set to "application/vnd.ms-excel" to indicate that the file is an Excel file. The content disposition header is set to "attachment" to indicate that the file should be downloaded as an attachment. The filename header is set to "sample.xlsx" to specify the name of the file. The cache-control header is set to "max-age=0" to indicate that the file should not be cached by the browser.
The writer object is then used to save the file to the output stream using the save method. The argument "php://output" specifies that the file should be sent to the output stream.
This is the basic structure of how to create an Excel file in PHP using PHPExcel. You can also add more data and format the cells as needed. For example, you can set the font size, font style, background color, and border style of cells. You can also add formulas, create charts, and add images to the worksheet.