yii2框架PhpSpreadsheet插件导入导出
时间: 2023-06-15 07:05:39 浏览: 235
Yii2框架是一个基于PHP的Web应用程序开发框架,而PhpSpreadsheet是一个用于操作Excel文件的PHP类库。结合使用Yii2和PhpSpreadsheet插件可以实现Excel文件的导入和导出功能。
以下是使用PhpSpreadsheet插件实现Excel文件导入和导出的示例代码:
1. Excel文件导入
在控制器中引入PhpSpreadsheet插件:
```php
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
```
在action中实现Excel文件导入:
```php
public function actionImportExcel()
{
$inputFileName = 'path/to/file.xlsx'; // 文件路径
$spreadsheet = IOFactory::load($inputFileName);
$worksheet = $spreadsheet->getActiveSheet();
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
for ($row = 1; $row <= $highestRow; ++$row) {
for ($col = 0; $col < $highestColumnIndex; ++$col) {
$cellValue = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
// 处理单元格数据
}
}
}
```
2. Excel文件导出
在控制器中引入PhpSpreadsheet插件:
```php
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
```
在action中实现Excel文件导出:
```php
public function actionExportExcel()
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World!');
$writer = new Xlsx($spreadsheet);
$filename = 'export.xlsx'; // 文件名称
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
}
```
以上是使用Yii2框架和PhpSpreadsheet插件实现Excel文件导入和导出的示例代码,可以根据实际需求进行修改。
阅读全文