下面以phpoffice的phpspreadsheet为例,phpspreadsheet是可以操作Excel的类库,
使用composer下载phpspreadsheet
composer require phpoffice/phpspreadsheet
把相关文件夹放到Yii2的vendor目录里面
配置vendor下的composer的autoload_psr4.php,由于依赖Psr的SimpleCache,所以这里需要新增两项
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'yii\\swiftmailer\\' => array($vendorDir . '/yiisoft/yii2-swiftmailer'),
'yii\\gii\\' => array($vendorDir . '/yiisoft/yii2-gii'),
'yii\\faker\\' => array($vendorDir . '/yiisoft/yii2-faker'),
'yii\\debug\\' => array($vendorDir . '/yiisoft/yii2-debug'),
'yii\\composer\\' => array($vendorDir . '/yiisoft/yii2-composer'),
'yii\\codeception\\' => array($vendorDir . '/yiisoft/yii2-codeception'),
'yii\\bootstrap\\' => array($vendorDir . '/yiisoft/yii2-bootstrap'),
'yii\\' => array($vendorDir . '/yiisoft/yii2'),
'cebe\\markdown\\' => array($vendorDir . '/cebe/markdown'),
'Faker\\' => array($vendorDir . '/fzaninotto/faker/src/Faker'),
//新增项
'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache'),
'PhpOffice\\PhpSpreadsheet\\' => array($vendorDir . '/phpoffice/PhpSpreadsheet'),
);
在控制器中使用
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
public function actionIndex()
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');
}