PHP_XLSXWriter 使用教程
原创 52cxy 08-23 14:38 阅读数:16930

PHP_XLSXWriter 是一个 PHP 库,用于生成 Excel 文件(.xlsx 格式)。它是一个轻量级、高效的库,特别适用于需要在 PHP 环境中创建 Excel 文件的应用场景。

功能特点

  • 支持 PHP 5.2.1+

  • 采用 UTF-8 编码的输入

  • 多个工作表

  • 支持货币/日期/数字单元格格式、简单公式

  • 支持基本单元格样式

  • 支持编写 100K+ 行的大型电子表格

  • 库的 API 设计简洁直观,易于理解和使用

  • 无需依赖 Excel 软件

  • 支持复杂的 Excel 格式


使用示例

  • 简单示例

include_once("xlsxwriter.class.php");

// 定义要导出的数据
$data = array(
    array('year', 'month', 'amount'),
    array('2024', '1', '220'),
    array('2024', '2', '153.5'),
);

$writer = new XLSXWriter();
$writer->writeSheet($data);
$writer->writeToFile('output.xlsx');
  • 指定单元格格式

include_once("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('2024-01-01', 873, 1, '44.00', 'misc', '=D2*0.05'),
    array('2024-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');


简单单元格格式映射到更高级的单元格格式

简单格式格式代码
string@
integer0
dateYYYY-MM-DD
datetimeYYYY-MM-DD HH:MM:SS
timeHH:MM:SS
price#,##0.00
dollar[$$-1009]#,##0.00;[RED]-[$$-1009]#,##0.00
euro#,##0.00 [$€-407];[RED]-#,##0.00 [$€-407]



Basic 单元格样式从 0.30 版本开始可用

样式可选值
fontArial, Times New Roman, Courier New, Comic Sans MS
font-size8,9,10,11,12 ...
font-stylebold, italic, underline, strikethrough or multiple ie: 'bold,italic'
borderleft, right, top, bottom, or multiple ie: 'top,left'
border-stylethin, medium, thick, dashDot, dashDotDot, dashed, dotted, double, hair, mediumDashDot, mediumDashDotDot, mediumDashed, slantDashDot
border-color#RRGGBB, ie: #ff99cc or #f9c
color#RRGGBB, ie: #ff99cc or #f9c
fill#RRGGBB, ie: #eeffee or #efe
haligngeneral, left, right, justify, center
valignbottom, center, distributed


共0条评论
我要评论