<?php
namespace app\common\library;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Excel
{
/**
* @param array $title 表头单元格内容
* @param array $data 从第二行开始写入的数据
* @param string $path Excel文件保存位置,路径中的目录必须存在
*
* @return null 没有设定返回值
*/
public static function export($title = [], $data = [], $name = '', $path = '')
{
$name = $name == '' ? date('YmdHis') : $name;
// 获取Spreadsheet对象
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// 表头单元格内容 第一行
$titCol = 'A';
foreach ($title as $value) {
// 单元格内容写入
$sheet->setCellValue($titCol . '1', $value);
$titCol++;
}
// 从第二行开始写入数据
$row = 2;
foreach ($data as $item) {
$dataCol = 'A';
foreach ($item as $value) {
// 单元格内容写入
$sheet->setCellValue($dataCol . $row, $value);
$dataCol++;
}
$row++;
}
if ($path == '') {
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
//删除清空:
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
exit;
} else {
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$result = $writer->save($path . $name . '.xlsx');
}
}
/**
* 读取excel文件内容
*/
public static function read($inputFileName)
{
$type = strtolower(pathinfo($inputFileName, PATHINFO_EXTENSION));
if ($type == 'xlsx' || $type == 'xls') {
$spreadsheet = IOFactory::load($inputFileName);
return $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
} else if($type == 'csv'){
$objReader = IOFactory::createReader('Csv')
->setDelimiter(',')
->setInputEncoding('GBK') //不设置将导致中文列内容返回boolean(false)或乱码
->setEnclosure('"')
->setSheetIndex(0);
$objPHPExcel = $objReader->load($inputFileName);
return $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
}
}
}
Excel 导出导入
于 2022-03-03 17:53:16 首次发布