Home > Article > Backend Development > How to output data to Excel table in PHP
During the use of PHP, how to output data in PHP to an Excel table? This article provides a total of two methods for your reference.
Method 1:
First, install the dependent library files, and composer installs the php processing excel class library.
composer require phpoffice/phpspreadsheet
Method of use
<?php // 类的自动加载 require 'vendor/autoload.php'; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); // 插入数据 $sheet->setCellValue('A1', '学号');//A列1行 $sheet->setCellValue('B1', '姓名'); $sheet->setCellValue('A2', '007'); $sheet->setCellValue('B2', '凌凌漆'); $writer = new Xlsx($spreadsheet); // 保存数据 $writer->save('user.xlsx');//文件存放路径
PS: Use
in ThinkPHP framework Method 2:
/** * 创建(导出)Excel数据表格 * @param array $list 要导出的数组格式的数据 * @param string $filename 导出的Excel表格数据表的文件名 * @param array $header Excel表格的表头 * @param array $index $list数组中与Excel表格表头$header中每个项目对应的字段的名字(key值) * 比如: $header = array('编号','姓名','性别','年龄'); * $index = array('id','username','sex','age'); * $list = array(array('id'=>1,'username'=>'YQJ','sex'=>'男','age'=>24)); * @return [array] [数组] */ function createtable($list,$filename,$header=array(),$index = array()){ header("Content-type:application/vnd.ms-excel"); header("Content-Disposition:filename=".$filename.".xls"); $teble_header = implode("\t",$header); $strexport = $teble_header."\r"; foreach ($list as $row){ foreach($index as $val){ $strexport.=$row[$val]."\t"; } $strexport.="\r"; } $strexport=iconv('UTF-8',"GB2312//IGNORE",$strexport); exit($strexport); }
Recommended: "php video tutorial" "php tutorial"
The above is the detailed content of How to output data to Excel table in PHP. For more information, please follow other related articles on the PHP Chinese website!