首先在工程内使用composer安装phpexcel:
composer require phpoffice/phpexcel
html部分:
<input type="file" id="img">
<input type="button" value="生成excel" onclick="create_excel">
js部分(formdata上传):
function create_excel(){
let imgfile = $('#img')[0].files[0];
let formdata = new FormData();
formdata.append('imgfile',imgfile);
$.ajax({
url: "{:url('test/read_excel')}",
data: formdata,
dataType: 'json',
type: 'post',
contentType: false,
processData: false,
success: function(res){
//代码块
}
});
}
后端控制器接收文件并调用读取方法:
//获取上传文件(此处应判断文件是否合法,可自行添加判断条件)
$imgfile = input('file.imgfile');
//生成路径和文件(路径可自定义,TP5.0版本可直接使用常量ROOT_PATH和DS)
$imgpath = Env::get('root_path').'public'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.'excel.xls';
$imgfile->move(Env::get('root_path').'public'.DIRECTORY_SEPARATOR.'uploads','excel.xls',true);
//读取并返回数据
$data = read_excel($imgpath);
return $data;
上面的read_excel为自定义方法,用于读取excel表格中的数据,参数为文件路径
function read_excel($filename)
{
//设置excel格式
$reader = PHPExcel_IOFactory::createReader('Excel2007');
//载入excel文件
$excel = $reader->load($filename);
//读取第一张表
$sheet = $excel->getSheet(0);
//获取总行数
$row_num = $sheet->getHighestRow();
//获取总列数
$col_num = $sheet->getHighestColumn();
$data = []; //数组形式获取表格数据
for($col='A';$col<=$col_num;$col++)
{
//从第二行开始,去除表头(若无表头则从第一行开始)
for($row=2;$row<=$row_num;$row++)
{
$data[$row-2][] = $sheet->getCell($col.$row)->getValue();
}
}
return $data;
}
表格获取数据如下: