先来说说写这个组件的初衷,接触yii2不是很久,在项目中刚好有这样一个excel导入导出的需求,筛选了多个组件, 但不是停止维护就是弃用,好不容易找到了一个可用的官方组件 phpoffice/phpspreadsheet,但是有点使用复杂,中文文档很少,但是不可否认这个组件功能很全面,代码质量比之前的phpExcel高出不少,于是就产生了写illusion/yii2-excel组件的想法,让导入和导出excel这件事情变得更新简单、易于上手,让大家的时间集中在创新和业务上面。最终就在读了phpoffice/phpspreadsheet的代码后,基于该组件写出现在的illusion/yii2-excel组件,希望大家能喜欢,同时,有什么使用不方便的地方或者代码方面的bug,欢迎大家提出建议或者贡献代码。
下载:composer require illusion/yii2-excel
(下面的代码示例,仅仅适用于1.2.0及1.2.0以下版本,若 使用最新版本,请参考https://packagist.org/packages/illusion/yii2-excel) 使用示例:
目前只支持csv、xls、xlsx三种电子表格的导出和导入
配置:
return [
'components' => [
'excel' => [
'class' => 'illusion\excel\Excel',
],
],
];
使用示例:
[
['部门', '组别', '姓名', '性别'],
['一米技术部', 'oms', 'illusion', '男'],
['一米技术部', 'oms', 'alex', '男'],
['一米技术部', 'pms', 'aaron', '女']
],
'two' => [
['类别', '名称', '价格'],
['文学类', '读者', '¥5'],
['科技类', 'AI之人工智能', '¥100'],
['科技类', '物联网起源', '¥500']
],
];
$spreadsheet = \Yii::$app->excel->createSpreadSheet('xls'); // 'xls' 自定义电子表格后缀
$spreadsheet->write($cellData);
$spreadsheet->download('department'); //'department' 自定义电子表格名
}
/**
* 读出电子表格的原生数据并根据自定义属性名装换成对应格式
* 然后根据你喜欢的方式将数据插入数据表
*
* @return array
*/
public function actionImport()
{
$transData = [];
$attributes = [
'department' => ['department', 'group', 'name', 'sex'], //'department' 工作表(sheet)名 键值:['department', 'group', 'name', 'sex']列对应的名称,名称顺序必须一致
'book' => ['category', 'book_name', 'price'],
];
if (\Yii::$app->request->isPost) {
$importFile = UploadedFile::getInstanceByName('file');
}
$fileName = explode('.', $importFile->name);
$spreadsheet = \Yii::$app->excel->createSpreadSheet($fileName[1]); // $fileName[1] 自定义电子表格后缀
$rawDatas = $spreadsheet->read($importFile->tempName); //$importFile->tempName 电子表(excel)路径
foreach ($rawDatas as $sheetName => $rawData) {
$transData[] = $spreadsheet->columnTo($rawData, $attributes[$sheetName]); //$rawData 读出的单个工作表(sheet)的原生数据,$attributes[$sheetName] $rawData电子表格中列按照顺序对应的自定义列名
}
return $transData;
}
/**
* 读出电子表格的原生数据
* 根据喜欢的方式插入数据表
*
* @return mixed
*/
public function actionImportRaw()
{
if (\Yii::$app->request->isPost) {
$importFile = UploadedFile::getInstanceByName('file');
}
$fileName = explode('.', $importFile->name);
$spreadsheet = \Yii::$app->excel->createSpreadSheet($fileName[1]); //同上注释
$rawDatas = $spreadsheet->read($importFile->tempName);
return $rawDatas;
}
}
技术交流:2016835341