应用场景

当遇到需要批量导入数据的时候,前端会上传一个excel表格,由后端读取数据并存入数据库。前端代码就不介绍了,这是一个前后端分离的项目,主要是讲解后端读取excel表格的数据。前端上传文件就可以了。
phpexcel 是什么
是用来操作office excel 文档的一个php类库,它基于微软的openxml标准和php语言。可以使用它来读取、写入不同格式的电子表格,如excel(biff).xls,excel 2007 (officeopenxml),.xlsx,csv,libre/openoffice calc .ods, gnumeric, pdf, html等等。
要求
php 5.2.0 版本及以上
php extension php_zip 开启 (如果你需要使用 phpexcel 来操作 .xlsx .ods or .gnumeric 文件)
php extension php_xml 开启
php extension php_gd2 开启(选填, 如果需要计算准确的列宽需要开启此扩展)
php 读取文件写入数据库
<?php
header("content-type:text/html; charset=utf-8");
// 制定允许其他域名访问
header("access-control-allow-origin:*");
// 响应类型
header('access-control-allow-methods:post');
// 响应头设置
header('access-control-allow-headers:x-requested-with, content-type');
// 数据库配置文件
include './config/config.php';
// 下载 phpexcel 放入项目内,引入即可
include "./phpexcel-1.8/classes/phpexcel/iofactory.php";
// 获取前端传入的文件
$file = $_files['file'];
//临时文件存放路径
$filetmp = $file['tmp_name'];
$filesize = $file['size'];
$filename = $file['name'];
//错误,输出0,表示文件提交成功
$fileerror = $file['error'];
if($fileerror==0) {
$inputfilename = $filetmp;
date_default_timezone_set('prc');
// 读取excel文件
try {
$inputfiletype = phpexcel_iofactory::identify($inputfilename);
$objreader = phpexcel_iofactory::createreader($inputfiletype);
$objphpexcel = $objreader->load($inputfilename);
} catch(exception $e) {
}
// 确定要读取的sheet,什么是sheet,看excel的右下角
$sheet = $objphpexcel->getsheet(0);
$highestrow = $sheet->gethighestrow();
$highestcolumn = $sheet->gethighestcolumn();
$time = date('y-m-d h:i:s', time());
// 把数据处理后存入数组
$array = array();
$time = date('y-m-d h:i:s', time());
for ($row = 2; $row <= $highestrow; $row++) {
$rowdata = $sheet->rangetoarray('a' . $row . ':' . $highestcolumn . $row, null, true, false);
// 重复数据不插入数据库
$falg = $rowdata[0][0];
$sqlif = "select codes from tablef where codes = '$falg'";
$querysql = mysqli_query($conn,$sqlif);
$arrsql = mysqli_fetch_array($querysql);
if($arrsql == null) {
// 获取到 excel 每行的数据插入数据库,需根据你自己的表格进行调整
$sql="insert into tablef(codes,year,month,idcode,type,timese) values('".$rowdata[0][0]."','" .($rowdata[0][1])."','".$rowdata[0][2]."','".$rowdata[0][3]."','".$rowdata[0][4]."','".$time."')";
$query=mysqli_query($conn,$sql);//函数执行一条 mysql 查询。
}
}
// 成功后返回给前端
echo json_encode(["msg" => 'ok']);
}else {
echo json_encode(["msg" => 'no']);
}
// 断开数据库连接
$conn->close();
?>结语
这是原生php使用的一个方式,我php的话只会一个 thinkphp 框架,这边我测试的话 thinkphp 使用起来跟这个也是差不多的,至于有些其他的php框架的话我没有用过,但是基本都差不多。现在前后端分离占主导地位,对于一些做后台的兄弟们来说,这些批量导入数据的是很常见的,这边就分享一个简单的,对于一些sql语句的话是需要修改的,这里面的sql语句是不安全的,这里提醒一下大家,测试的时候使用这些sql语句为啥问题,生产环境切记不能这样用。
到此这篇关于php使用phpexcel读取excel数据并批量上传到数据库的文章就介绍到这了,更多相关php phpexcel读取excel内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论