简单封装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 数据
*/
public function export($field, $data)
{
$Spreadsheet = $this->Spreadsheet;
$sheet = $Spreadsheet->getActiveSheet();
$sheet->getStyle('A1:I' . (count($data) + 1))->getFont()->setName('宋体');
$fieldABC = range('A', 'Z');
foreach ($field as $k => $v) {
$sheet->setCellValue($fieldABC[$k] . '1', $v)->getColumnDimension($fieldABC[$k])->setAutoSize(TRUE);
}
$i = 1;
foreach ($data as $rk => $row) {
$i++;
foreach ($field as $k => $v) {
foreach ($row as $key => $value) {
$sheet->setCellValue($fieldABC[$k] . $i, $value);
}
}
}
$writer = new Xlsx($Spreadsheet);
return $writer->save('php://output');
return $writer;
}
/**
* 读取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;
}
}
标签:xlsx,Spreadsheet,getHighestColumn,PhpSpreadsheet,start,param,PHP,data
From: https://www.cnblogs.com/xfstu/p/17890758.html