要使用純PHP建立或編輯Excel電子表格,我們將使用PHPExcel庫,它可以讀寫許多電子表格格式,包括xls,xlsx,ods和csv。 在我們繼續之前,請仔細檢查您的伺服器上是否有PHP 5.2或更高版本以及安裝了以下PHP擴充:php_zip,php_xml和php_gd2。
建立電子表格
#建立電子表格是PHP應用程式中最常見的用例之一,用於將資料匯出到Excel電子表格。請查看以下程式碼,了解如何使用PHPExcel建立範例Excel電子表格: (建議學習:PHP視訊教學)
// 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');
如果要下載電子表格而不是將其儲存到伺服器,請執行以下操作:
header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="file.xlsx"'); header('Cache-Control: max-age=0'); $writer->save('php://output');
以上是php語言怎麼做表格的詳細內容。更多資訊請關注PHP中文網其他相關文章!