基于thinkphp怎么做到将execle 表格上传并插入数据库?支招支招!!
PHPExcel安装这个类库
<!--前端-->
<form action="/index/index/upload" enctype="multipart/form-data" method="post">
<input type="file" name="excel_file" /> <br>
<input type="submit" value="上传" />
</form>
```php
//后端在控制器中
public function upload(){
// 获取表单上传文件
$file = request()->file('excel_file');
// 移动到框架应用根目录/uploads/ 目录下
$info = $file->move( '../uploads');
if($info){
// 成功上传后 获取上传信息
$excelFilePath = $info->getExtension();
//这边将$excelFilePath 存入你数据库的就行了
}else{
// 上传失败获取错误信息
echo $file->getError();
}
前端弄一个form表单,将要上传的excel文件上传到后端
<form method="post" action="对应的后端地址" enctype="multipart/form-data">
选择文件:<input type="file" name="excel" id="excel"/>
<button type="submit">上传</button>
</form>
后端代码:
<?php
$upload = new \Think\Upload(); // 实例化上传类
$upload->maxSize = 5242880; // 设置附件上传大小
$upload->exts = array('xlsx', 'xls'); // 设置附件上传类型
$upload->rootPath = './'; // 设置附件上传根目录
// 上传单个文件
$info = $upload->uploadOne($_FILES['excel']);
if (!$info) { // 上传错误提示错误信息
$this->error($upload->getError());
} else {
//上传Excel成功
$exts = $info['ext'];
$file_name = $info['savepath'] . $info['savename'];
$res = getdata($file_name, $exts);
// $res 中就是excel中存放的内容,将内容根据数库表的字段存入数据库即可
$saveData = [];
foreach($res as $key => $value){
// 每一行对应的key值
$saveData['key1'] = $value[0];
$saveData['key2'] = $value[1];
$saveData['key3'] = $value[2];
$saveData['key4'] = $value[3];
// 有多少就写多少
}
// 保存
$result = M('要存的数据表')->addAll($saveData);
// 返回结果
echo "根据result的结果输出结果,逻辑自己写";
}
function getdata($file_name, $exts = 'xls')
{
//导入PHPExcel类库,因为PHPExcel没有用命名空间,只能inport导入
import("Org.Util.PHPExcel");
//创建PHPExcel对象,注意,不能少了
$PHPExcel = new \PHPExcel();
if ($exts == 'xlsx') {
import("Org.Util.PHPExcel.Reader.Excel2007"); //引入2007的库
$PHPReader = new \PHPExcel_Reader_Excel2007();
} else if ($exts == 'xls') {
import("Org.Util.PHPExcel.Reader.Excel5"); //引入excel5的库
$PHPReader = new \PHPExcel_Reader_Excel5();
}
//载入文件
$PHPExcel = $PHPReader->load($file_name);
//获取表中的第一个工作表,如果要获取第二个,把0改为1,依次类推
$currentSheet = $PHPExcel->getSheet(0);
//获取总列数
$allColumn = $currentSheet->getHighestColumn();
//获取总行数
$allRow = $currentSheet->getHighestRow();
$excelData = array();
//循环获取表中的数据,$currentRow表示当前行,从哪行开始读取数据,索引值从0开始
for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
//从哪列开始,A表示第一列
for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
//数据坐标
$address = $currentColumn . $currentRow;
$excelData[$currentRow][$currentColumn] = (string) $currentSheet->getCell($address)->getValue();
}
}
return $excelData;
}