安利一个简单好用的PHP生成excel文件类

京漂大叔 2019-09-24 AM 262℃ 0条

今天发现一个简单好用的PHP生成excel文件类,分享给大家。
PHP_XLSXWriter:PHP_XLSXWriter类的github地址

这个类可以很方便的生成excel文件,做导出,邮件发送都很方便,简单到想哭,看看下面的列子,有某有?

require_once("/PHP_XLSXWriter-master/xlsxwriter.class.php");
$data = array(
    array('year','month','amount'),
    array('2003','1','220'),
    array('2003','2','153.5'),
);

$writer = new XLSXWriter();
$writer->writeSheet($data);
$writer->writeToFile('output.xlsx');

上面的是一个没有表头的案例,在分享一个有表头的案例。
下面的header数组就是excel的表头,数组里面的key就是表头的名称,valur值是指定表头是什么类型,比如:日期,文本,字符串,还是数字等。

require_once("/PHP_XLSXWriter-master/xlsxwriter.class.php");
$header = array(
  'created'=>'date',
  'product_id'=>'integer',
  'quantity'=>'#,##0',
  'amount'=>'price',
  'description'=>'string',
  'tax'=>'[$$-1009]#,##0.00;[RED]-[$$-1009]#,##0.00',
);
$data = array(
    array('2015-01-01',873,1,'44.00','misc','=D2*0.05'),
    array('2015-01-12',324,2,'88.00','none','=D3*0.05'),
);

$writer = new XLSXWriter();
$writer->writeSheetHeader('Sheet1', $header );
foreach($data as $row)
    $writer->writeSheetRow('Sheet1', $row );
$writer->writeToFile('example.xlsx');

在来一个导出的案例,copy运行就可以直接导出

include_once("xlsxwriter.class.php");
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);
$filename = "example.xlsx";
header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$rows = array(
    array('2003','1','-50.5','2010-01-01 23:00:00','2012-12-31 23:00:00'),
    array('2003','=B1', '23.5','2010-01-01 00:00:00','2012-12-31 00:00:00'),
);
$writer = new XLSXWriter();
$writer->setAuthor('Some Author'); 
foreach($rows as $row)
    $writer->writeSheetRow('Sheet1', $row);
$writer->writeToStdOut();
//$writer->writeToFile('example.xlsx');
//echo $writer->writeToString();
exit(0);

注意上面的案例在使用之前,要先引入PHP_XLSXWriter类文件
是不是简单易用到爆呢,没有骗你吧,我也找了好久,终于找到这么一简单到哭的PHP生成excel类,赶紧去尝试一下吧。

标签: PHP, excel类, PHP_XLSXWriter

非特殊说明,文章均为原创。