这篇文章将为大家详细讲解有关TP5.1excel导入数据库的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
在用之前必须
use think\PHPExcel;
并且这个是第三方类库,这个类库是直接用命令能后下载的
composer 命令:
composer require phpoffice/phpexcel
public function save(){
//前台的form表单大家都会吧,我就不写了
//设置文件上传的最大限制
ini_set('memory_limit','1024M');
//加载第三方类文件
require_once "../extend/PHPExcel/PHPExcel.php";
//防止乱码
header("Content-type:text/html;charset=utf-8");
//实例化主文件
//接收前台传过来的execl文件
$file = $_FILES['file'];
//截取文件的后缀名,转化成小写
$extension = strtolower(pathinfo($file['name'],PATHINFO_EXTENSION));
if($extension == "xlsx"){
//2007(相当于是打开接收的这个excel)
$objReader =\PHPExcel_IOFactory::createReader('Excel2007');
}else{
//2003(相当于是打开接收的这个excel)
$objReader = \PHPExcel_IOFactory::createReader('Excel5');
}
$objContent = $objReader -> load($file['tmp_name']);
if ($objContent){
$sheetContent = $objContent -> getSheet(0) -> toArray();
//删除第一行标题
//dump($sheetContent);die;
//其实到这里就结束了,就已经得到excel表格的所有数据了,下面就是如何插入数据库的问题了 ,下面我的方法大家可以参考
$len = count($sheetContent);
//var_dump($len);exit;
if($len == 1){
echo "<script>alert('请不要拿空表格来骗我');window.history.back();</script>";
exit();
}
for($i = 1;$i<$len; $i++){
$data = [
'id' => '',
'phone' => $sheetContent[$i][0],
'company_name' => $sheetContent[$i][1],
'add_id' => $sheetContent[$i][2],
'industry_id' => $sheetContent[$i][3],
'data_name' => $sheetContent[$i][4],
'data_address' => $sheetContent[$i][5],
'data_class' => $sheetContent[$i][6],
'data_set_up_date' => $sheetContent[$i][6],
'create_time' => date('Y-m-d')
];
//dump($data);die;
$re = Db::name('data_decoration_company')->insert($data);
}
//var_dump($res);die;
if($re){
echo "<script>alert('导入成功');window.history.back();</script>";
exit();
$this->redirect('/')->remember();
}else{
echo "<script>alert('导入失败了,慢点慢点@!@本电脑的脑子已经跟不上你的节奏了');window.history.back();</script>";
exit();
$this->redirect('/')->remember();
}
}else{
$this->error('请导入表格 !');
}
}
关于“TP5.1excel导入数据库的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/5064233/blog/5037718