To create or edit Excel spreadsheets using pure PHP, we will use the PHPExcel library, which can read and write many spreadsheet formats, including xls, xlsx, ods, and csv. Before we continue, double check that you have PHP 5.2 or higher on your server and that the following PHP extensions are installed: php_zip, php_xml, and php_gd2.
Creating spreadsheets
Creating spreadsheets is one of the most common use cases in PHP applications for Export data to Excel spreadsheet. Check out the following code to learn how to create a sample Excel spreadsheet using PHPExcel: (Recommended learning: PHP Video Tutorial)
// Include PHPExcel library and create its object require('PHPExcel.php'); $phpExcel = new PHPExcel; // Set default font to Arial $phpExcel->getDefaultStyle()->getFont()->setName('Arial'); // Set default font size to 12 $phpExcel->getDefaultStyle()->getFont()->setSize(12); // Set spreadsheet properties – title, creator and description $phpExcel ->getProperties()->setTitle("Product list"); $phpExcel ->getProperties()->setCreator("Voja Janjic"); $phpExcel ->getProperties()->setDescription("PHP Excel spreadsheet testing."); // Create the PHPExcel spreadsheet writer object // We will create xlsx file (Excel 2007 and above) $writer = PHPExcel_IOFactory::createWriter($phpExcel, "Excel2007"); // When creating the writer object, the first sheet is also created // We will get the already created sheet $sheet = $phpExcel ->getActiveSheet(); // Set sheet title $sheet->setTitle('My product list'); // Create spreadsheet header $sheet ->getCell('A1')->setValue('Product'); $sheet ->getCell('B1')->setValue('Quanity'); $sheet ->getCell('C1')->setValue('Price'); // Make the header text bold and larger $sheet->getStyle('A1:D1')->getFont()->setBold(true)->setSize(14); // Insert product data // Autosize the columns $sheet->getColumnDimension('A')->setAutoSize(true); $sheet->getColumnDimension('B')->setAutoSize(true); $sheet->getColumnDimension('C')->setAutoSize(true); // Save the spreadsheet $writer->save('products.xlsx');
If you want to download the spreadsheet instead of saving it to the server , please do the following:
header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="file.xlsx"'); header('Cache-Control: max-age=0'); $writer->save('php://output');
The above is the detailed content of How to make a form in php language. For more information, please follow other related articles on the PHP Chinese website!