当前位置:Gxlcms > PHP教程 > php语言怎么做表格

php语言怎么做表格

时间:2021-07-01 10:21:17 帮助过:62人阅读

要使用纯PHP创建或编辑Excel电子表格,我们将使用PHPExcel库,它可以读写许多电子表格格式,包括xls,xlsx,ods和csv。在我们继续之前,仔细检查您的服务器上是否有PHP 5.2或更高版本以及安装了以下PHP扩展:php_zip,php_xml和php_gd2。

创建电子表格

创建电子表格是PHP应用程序中最常见的用例之一,用于将数据导出到Excel电子表格。查看以下代码,了解如何使用PHPExcel创建示例Excel电子表格: (推荐学习:PHP视频教程)

  1. // Include PHPExcel library and create its object
  2. require('PHPExcel.php');
  3. $phpExcel = new PHPExcel;
  4. // Set default font to Arial
  5. $phpExcel->getDefaultStyle()->getFont()->setName('Arial');
  6. // Set default font size to 12
  7. $phpExcel->getDefaultStyle()->getFont()->setSize(12);
  8. // Set spreadsheet properties – title, creator and description
  9. $phpExcel ->getProperties()->setTitle("Product list");
  10. $phpExcel ->getProperties()->setCreator("Voja Janjic");
  11. $phpExcel ->getProperties()->setDescription("PHP Excel spreadsheet testing.");
  12. // Create the PHPExcel spreadsheet writer object
  13. // We will create xlsx file (Excel 2007 and above)
  14. $writer = PHPExcel_IOFactory::createWriter($phpExcel, "Excel2007");
  15. // When creating the writer object, the first sheet is also created
  16. // We will get the already created sheet
  17. $sheet = $phpExcel ->getActiveSheet();
  18. // Set sheet title
  19. $sheet->setTitle('My product list');
  20. // Create spreadsheet header
  21. $sheet ->getCell('A1')->setValue('Product');
  22. $sheet ->getCell('B1')->setValue('Quanity');
  23. $sheet ->getCell('C1')->setValue('Price');
  24. // Make the header text bold and larger
  25. $sheet->getStyle('A1:D1')->getFont()->setBold(true)->setSize(14);
  26. // Insert product data
  27. // Autosize the columns
  28. $sheet->getColumnDimension('A')->setAutoSize(true);
  29. $sheet->getColumnDimension('B')->setAutoSize(true);
  30. $sheet->getColumnDimension('C')->setAutoSize(true);
  31. // Save the spreadsheet
  32. $writer->save('products.xlsx');

如果要下载电子表格而不是将其保存到服务器,请执行以下操作:

  1. header('Content-Type: application/vnd.ms-excel');
  2. header('Content-Disposition: attachment;filename="file.xlsx"');
  3. header('Cache-Control: max-age=0');
  4. $writer->save('php://output');

以上就是php语言怎么做表格的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行