PHPExcel上一版本1.8.1于2015年发布。该项目已不再维护,可以使用,但是不建议再使用。所有用户都应该迁移到其直接后继者PhpSpreadsheet或其他替代方案。PhpSpreadsheet打破了兼容性,大大提高了代码库质量(命名空间,PSR合规性,最新PHP语言功能的使用等)。
虽然 PHPExcel 不在维护 但是 也要写一下PHPexcel 导入导出
第一步 下载 PHPexcel 包
composer 下载
composer require phpoffice/phpspreadsheet:1.6.*
第二步 导出 方法
public function actionExcel()
{
include('../PHPExcel/Classes/PHPExcel.php');//引用PHPExcel.php
$data = Gouzi::find()->asArray()->one(); //获取 数据表 字段
foreach ($data as $key => $value) {
$arr[$key] = $key;
}
$data1 = Gouzi::find()->asArray()->all();
array_unshift($data1, $arr);//将数据表字段与数据结合成一个数组
$r = new \PHPExcel();
$r->getActiveSheetIndex(0);
foreach ($data1 as $key => $value) {
$z = ++$key;//$z 这里代替A1 A2 。。。。后面的数字
$r->getActiveSheet()->setCellValue('A' . $z, $value['id']);
$r->getActiveSheet()->setCellValue('B' . $z, $value['email']);
$r->getActiveSheet()->setCellValue('C' . $z, $value['pwd']);
$r->getActiveSheet()->setCellValue('D' . $z, $value['tel']);
}
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="abcfd.xls"');//两个header头代表 下载zip压缩包
$b = new \PHPExcel_Writer_Excel5($r);
$b->save('php://output');
die;
}
这里导出就完成了 是不是很简单啊;
第三步 导入
前台
<?php $form = ActiveForm::begin([
'action' => Url::to(['user/into']),
'options' =>['enctype'=>'multipart/form-data']
])?>
<input type="file" name="file">
<button type="submit" class="btn">导入数据</button>
<?php ActiveForm::end()?>
后台
public function actionInto()
{
include("../PHPExcel/Classes/PHPExcel/IOFactory.php");//应用文件
$filePath = $_FILES['file']['tmp_name'];
$objPHPExcelReader = \PHPExcel_IOFactory::load($filePath);
$sheet = $objPHPExcelReader->getSheet(0); // 读取第一个工作表(编号从 0 开始)
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
$arr = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
// 一次读取一列
$res_arr = array();
for ($row = 2; $row <= $highestRow; $row++) {
$row_arr = array();
for ($column = 0; $arr[$column] != 'D'; $column++) {
$val = $sheet->getCellByColumnAndRow($column, $row)->getValue();
$row_arr[] = $val;
}
$res_arr[] = $row_arr;
}
$model = new Gouzi();
$con = \Yii::$app->db;
$res = $con->createCommand()->batchInsert("gouzi", ['email', 'pwd', 'tel'], $res_arr)->execute();
}