Home >Backend Development >PHP Problem >How to output data to Excel table in PHP

How to output data to Excel table in PHP

autoload
autoloadOriginal
2021-03-26 14:53:504491browse

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 &#39;vendor/autoload.php&#39;;
 
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
 
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// 插入数据
$sheet->setCellValue(&#39;A1&#39;, &#39;学号&#39;);//A列1行
$sheet->setCellValue(&#39;B1&#39;, &#39;姓名&#39;);
$sheet->setCellValue(&#39;A2&#39;, &#39;007&#39;);
$sheet->setCellValue(&#39;B2&#39;, &#39;凌凌漆&#39;);
$writer = new Xlsx($spreadsheet);
// 保存数据
$writer->save(&#39;user.xlsx&#39;);//文件存放路径

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(&#39;编号&#39;,&#39;姓名&#39;,&#39;性别&#39;,&#39;年龄&#39;); 
 *       $index = array(&#39;id&#39;,&#39;username&#39;,&#39;sex&#39;,&#39;age&#39;); 
 *       $list = array(array(&#39;id&#39;=>1,&#39;username&#39;=>&#39;YQJ&#39;,&#39;sex&#39;=>&#39;男&#39;,&#39;age&#39;=>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(&#39;UTF-8&#39;,"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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn