要使用纯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 objectrequire('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语言怎么做表格的详细内容。