简单封装PhpSpreadsheet,实现PHP快速导入、导出xlsx
简单封装PhpSpreadsheet,实现PHP快速导入、导出xlsx
<?php
namespace xfstu\tools;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
/**
* @method export(array $field, array $data) 简单封装导出xlsx
* @method getFileArray(string $fileName, int $start = 2, string $getHighestColumn = 'auto') 简单封装读取xlsx
*/
class ToolsXlsx
{
public $Spreadsheet;
public function __construct()
{
$this->Spreadsheet = new Spreadsheet();
}
/**
* 导出二维数组到xlsx
* @param array $field 字段名称
* @param array $data
* @param callable $callback 回调
*/
public function export($field, $data, $callback = null)
{
$Spreadsheet = $this->Spreadsheet;
$sheet = $Spreadsheet->getActiveSheet();
$fieldABC = array_slice(range('A', 'Z'), 0, count($field));
$sheet->getStyle('A1:' . end($fieldABC) . '' . (count($data) + 1))->getFont()->setName('宋体');
foreach ($field as $k => $v) {
$sheet->setCellValue($fieldABC[$k] . '1', $v);
}
for ($i = 0; $i < count($data); $i++) {
if ($callback) {
$row = $callback($data[$i]);
} else {
$row = $data[$i];
}
for ($j = 0; $j < count($field); $j++) {
$sheet->setCellValue($fieldABC[$j] . ($i + 2), $row[$field[$j]])->getColumnDimension($fieldABC[$j])->setAutoSize(TRUE);
}
}
$writer = new Xlsx($Spreadsheet);
return $writer->save('php://output');
}
/**
* 读取xlsx
* @param string $fileName
* @param int $start
* @param string $getHighestColumn
* @return array
*/
public function getFileArray($fileName, $start = 2, $getHighestColumn = 'auto')
{
$spreadsheet = IOFactory::load($fileName);
$worksheet = $spreadsheet->getActiveSheet();
$highestRow = $worksheet->getHighestRow();
$highestColumn = $getHighestColumn == 'auto' ? $worksheet->getHighestColumn() : $getHighestColumn;
$data = [];
for ($start; $start <= $highestRow; ++$start) {
$rows = $worksheet->rangeToArray('A' . $start . ':' . $highestColumn . $start, null);
$data[] = $rows[0];
}
return $data;
}
}
本文来自博客园,作者:小枫同学,除网络转载的部分,其他版权属于作者和博客园所有,未经作者或博客园许可,禁止转载、复制、重新发布完整或者部分文字、代码、图片等信息,否则将保留追究法律责任的权利(如博客侵权了您的作品,本人再次表示抱歉,请将原创地址发送至下文邮箱,核实后立刻删除。)。查阅文章的同学,由于网络爬虫严重,有些代码并不会完整贴出来或者存在bug,不过你可以发送邮件到xfstune@126.com获取新代码,记得附上文章链接