PhpSpreadsheet 导入导出基础应用
由于PHPExcel已经不再维护,PhpSpreadsheet是PHPExcel的下一个版本。PhpSpreadsheet是一个用纯PHP编写的库,并引入了命名空间,PSR规范等。这里简单介绍下PhpSpreadsheet的导入导出功能。
1、安装
使用composer安装:composer require phpoffice/phpspreadsheet
GitHub下载:https://github.com/PHPOffice/PhpSpreadsheet
2、excel文件导出
// 命名空间引入
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
/**
* @title export 导出
*/
public function export() {
$data = [
['title1' => '111', 'title2' => '222'],
['title1' => '111', 'title2' => '222'],
['title1' => '111', 'title2' => '222']
];
$title = ['标题1', '标题2'];
array_unshift($data, $title);
// Create new Spreadsheet object
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet()->setTitle('工作表标题');
foreach ($data as $k => $item) {
$column = 1;
foreach ($item as $value) {
// 因不想定义 A… 一大串大写字母 所以使用数字单元格坐标设置单元格值。
$sheet->setCellValueByColumnAndRow($column, $k + 1, $value);
$column++;
}
}
// Redirect output to a client’s web browser (Xlsx)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
exit;
}
3、读取excel文件内容
/**
// 命名空间引入
use PhpOffice\PhpSpreadsheet\IOFactory;
* @title readExcel 读取excel文件内容
* @return array
*/
public function readExcel() {
$inputFileName = './test.xlsx';
$spreadsheet = IOFactory::load($inputFileName);
// toArray() 具体参数参考官方文档
$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
return $sheetData;
}
添加新评论