很多时候需要导入excel里的数据,先下载https://github.com/PHPOffice/PHPExcel
或者用composer require phpoffice/phpexcel下载
先将Excel表上传到服务器--->然后将表格里面的数据读取出来保存在数组里--->再讲将数组里面的数据添加至数据库。
前端代码:
layui.use('upload', function () {
var upload = layui.upload;
//执行实例
var uploadInst = upload.render({
elem: '#demo' //绑定元素
, url: "{:url('exams/uploadExecl')}" //上传接口
, accept: 'file'
, done: function (res) {
//上传完毕回调
if (res.code == 2) {
} else {
layer.msg(res.msg);
}
}
, error: function () {
//错误处理
}
});
});
后端:
// 执行数据导入
public function doImport()
{
$excel = request()->file('file')->getInfo(); //excel为file文件信息数组
$objPHPExcel = \PHPExcel_IOFactory::load($excel['tmp_name']);
$sheet_count = $objPHPExcel->getSheetCount(); //获取当前文件页数
for ($s = 0; $s < $sheet_count; $s++) {
$currentSheet = $objPHPExcel->getSheet($s); // 当前页
$row_num = $currentSheet->getHighestRow(); // 当前页行数
$col_max = $currentSheet->getHighestColumn(); // 当前页最大列号
$d = 0;
for ($i = 1; $i <= $row_num; $i++) {
for ($j = 'A'; $j <= $col_max; $j++) {
$address = $j . $i; // 单元格坐标
$cell_values[$d][] = $currentSheet->getCell($address)->getFormattedValue();
}
$d++;
}
return $cell_values;
}
}
文件内容
简单做了下输出,
0条评论