thinkphp添加excel更新数据表数据(优化篇)
由于主管说使用saveAll更新数据效率太低,要改用sql语句一次执行现在修改
/**
* excel开启上传
* author: panzhide
* @return array
* Date: 2021/4/14
*/
public function logisticsImportExcel()
{
$file = request()->file('file');
if (!$file) {
return json_success('excel文件不能为空', 'file');
}
//将文件保存到public/storage/uploads/目录下面
$savename = \think\Facade\Filesystem::disk('public')->putFile('uploads', $file); //获取文件路径
$filePath = getcwd() . '/storage/' . $savename;
if (!is_file($filePath)) {
return json_success('没有发现结果');
}
//实例化reader
$ext = pathinfo($filePath, PATHINFO_EXTENSION);
if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
return json_success('未知的数据格式');
}
if ($ext === 'csv') {
$file = fopen($filePath, 'r');
$filePath = tempnam(sys_get_temp_dir(), 'import_csv');
$fp = fopen($filePath, "w");
$n = 0;
while ($line = fgets($file)) {
$line = rtrim($line, "\n\r\0");
$encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
if ($encoding != 'utf-8') {
$line = mb_convert_encoding($line, 'utf-8', $encoding);
}
if ($n == 0 || preg_match('/^".*"$/', $line)) {
fwrite($fp, $line . "\n");
} else {
fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
}
$n++;
}
fclose($file) || fclose($fp); $reader = new Csv();
} elseif ($ext === 'xls') {
$reader = new Xls();
} else {
$reader = new Xlsx();
} //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
$importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
//默认的表名
$table = OrderAddress::build()->getTable(); $fieldArr = [];
$list = Db::query('SHOW FULL COLUMNS FROM `' . $table . '`');
foreach ($list as $k => $v) {
if ($importHeadType == 'comment') {
$fieldArr[$v['Comment']] = $v['Field'];
} else {
$fieldArr[$v['Field']] = $v['Field'];
}
} //加载文件
$update_data = []; // 需要更新的数据
$time = time();
try {
if (!$PHPExcel = $reader->load($filePath)) {
return json_success('未知的数据格式');
}
$currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
// $currentSheet -> setReadDataOnly(true);
$allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
$allRow = $currentSheet->getHighestRow(); //取得一共有多少行
$maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
$fields = [];
for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
$fields[] = $val;
}
}
if (!in_array('物流公司', $fields)) {
return json_error('缺少物流公司列');
}
if (!in_array('物流编号', $fields)) {
return json_error('缺少物流编号列');
} $max_row = 5000;
if ($allRow > $max_row) {
return json_error("每次最多导入${max_row}条数据");
} $kuaidi_code_data = KuaidiCode::build() -> column('code', 'name'); // 查询当前支持的所有物流公司 for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
$values = [];
for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
if ($currentColumn == 4 && is_numeric($val)) { // 如果时间是数字类型,需要转格式
$toTimestamp = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($val);
$date = date("Y-m-d", $toTimestamp );
$val = $date;
}
$values[] = is_null($val) ? '' : $val;
}
$row = [];
// dump($values);
$temp = array_combine($fields, $values);
foreach ($temp as $k => $v) {
if (isset($fieldArr[$k]) && $k !== '') {
$row[$fieldArr[$k]] = $v;
}
}
if ($row) {
if ($row['kuaidicom'] || $row['logistics_sn']) { // 只处理kuaidicom或者logistics_sn有内容的数据
if (!$row['kuaidicom']) {
$error[] = '第' . $currentRow . '行物流公司不得为空';
} elseif (!$row['logistics_sn']) {
$error[] = '第' . $currentRow . '行物流编号不得为空';
} else {
// 判断物流公司是否合法
$kuaidicom_code = $kuaidi_code_data[$row['kuaidicom']] ?? ''; // 物流公司对应编码
if ($kuaidicom_code) {
$row['kuaidicom_code'] = $kuaidicom_code; // 物流公司对应编码
$row['shipping_time'] = strtotime($row['shipping_time']) ; // 发货时间
$update_data[] = $row;
} else {
$error[] = '第' . $currentRow . '行物流公司名称"'.$row['kuaidicom'].'"错误或系统不支持';
}
}
}
}
}
} catch (Exception $exception) {
return json_success($exception->getMessage());
} if (!$update_data) {
return json_success('没有更新行');
}
$n = 0;
Db::startTrans();
try {
$this -> logisticsImportExcelUpdate($update_data);
Db::commit();
} catch (\Exception $e) {
Db::rollback();
$msg = $e->getMessage();
return json_error($msg);
} $msg = '成功导入' . count($update_data) . '条数据,失败'.count($error).'条数据';
$data['complete'] = 1;
$data['error'] = $error;
return json_success($msg, $data);
} private function logisticsImportExcelUpdate($update_data)
{
// 整合更新语句
$update_value_sql = '';
$update_id_sql = '';
$update_key = ['kuaidicom', 'kuaidicom_code', 'logistics_sn'];
foreach ($update_key as $key) {
$n = 0;
foreach ($update_data as $value) {
$n ++;
if ($n == 1) {
$update_value_sql .= $key." = CASE order_sn ";
}
$update_value_sql .= 'WHEN \''.$value['order_sn'].'\' THEN \''.$value[$key].'\'';
if ($n != count($update_data)) {
$update_value_sql .= " ";
} else {
$update_value_sql .= " END,";
}
}
}
$update_value_sql = substr($update_value_sql,0,strlen($update_value_sql)-1);
$n = 0;
foreach ($update_data as $value) {
$n ++;
if ($n == 1) {
$update_id_sql .= "(";
}
$update_id_sql .= ' \''.$value['order_sn'].'\' ';
if ($n != count($update_data)) {
$update_id_sql .= ",";
} else {
$update_id_sql .= ")";
}
}
if (count($update_data)) {
$update_sql = 'UPDATE cy_order_address SET '.$update_value_sql.' WHERE order_sn IN '.$update_id_sql.';';
Db::query($update_sql); // 执行更新语句,更新订单地址表 物流公司、物流编号、物流公司编号
} // 整合更新语句
$update_value_sql = '';
$update_id_sql = '';
$update_key = ['shipping_time'];
foreach ($update_key as $key) {
$n = 0;
foreach ($update_data as $value) {
$n ++;
if ($n == 1) {
$update_value_sql .= $key." = CASE order_sn ";
}
$update_value_sql .= 'WHEN \''.$value['order_sn'].'\' THEN \''.$value[$key].'\'';
if ($n != count($update_data)) {
$update_value_sql .= " ";
} else {
$update_value_sql .= " END,";
}
}
}
$update_value_sql = substr($update_value_sql,0,strlen($update_value_sql)-1);
$n = 0;
foreach ($update_data as $value) {
$n ++;
if ($n == 1) {
$update_id_sql .= "(";
}
$update_id_sql .= ' \''.$value['order_sn'].'\' ';
if ($n != count($update_data)) {
$update_id_sql .= ",";
} else {
$update_id_sql .= ")";
}
}
if (count($update_data)) {
$update_sql = 'UPDATE cy_order SET '.$update_value_sql.' WHERE order_sn IN '.$update_id_sql.';';
Db::query($update_sql); // 执行更新语句,更新订单表 发货时间
}
}
thinkphp添加excel更新数据表数据(优化篇)的更多相关文章
- 追踪app崩溃率、事件响应链、Run Loop、线程和进程、数据表的优化、动画库、Restful架构、SDWebImage的原理
1.如何追踪app崩溃率,如何解决线上闪退 当 iOS设备上的App应用闪退时,操作系统会生成一个crash日志,保存在设备上.crash日志上有很多有用的信息,比如每个正在执行线程的完整堆栈 跟踪信 ...
- ASP.NET网页动态添加、更新或删除数据行
ASP.NET网页动态添加.更新或删除数据行 看过此篇<ASP.NET网页动态添加数据行> http://www.cnblogs.com/insus/p/3247935.html的网友,也 ...
- MySQL<添加、更新与删除数据>
添加.更新与删除数据 添加数据 为表中所有字段添加数据 INSERT INTO 表名(字段名1,字段名2,……) VALUES(值1,值2,……); insert into 表名 values(值1, ...
- 09Oracle Database 数据表数据插入,更新,删除
Oracle Database 数据表数据插入,更新,删除 插入数据 Insert into table_name(column) values(values); insert into studen ...
- MySQL触发器更新本表数据异常:Can't update table 'tbl' in stored function/trigger because it
MySQL触发器更新本表数据异常:Can't update table 'tbl' in stored function/trigger because it 博客分类: 数据库 MySQLJava ...
- mssql sqlserver 三种数据表数据去重方法分享
摘要: 下文将分享三种不同的数据去重方法数据去重:需根据某一字段来界定,当此字段出现大于一行记录时,我们就界定为此行数据存在重复. 数据去重方法1: 当表中最在最大流水号时候,我们可以通过关联的方式为 ...
- SQL Server2016导出数据表数据
SQL Server2016导出数据表数据 高文龙关注0人评论3914人阅读2017-09-22 08:41:56 SQL Server2016导出数据表数据 我们前面已经介绍了很多关于SQL Ser ...
- Django学习之天气调查实例(2):显示数据表数据
数据表数据添加后,如添加3条用户信息,分别为“aaa”.“bbb”.“ccc”,现在通过代码的方式显示数据表中的数据. 1.在website项目文件夹中创建 userload.py文件,并且写如下代码 ...
- 10Oracle Database 数据表数据查询
Oracle Database 数据表数据查询 DML 数据操纵语言 - 数据的查看和维护 select / insert /delete /update 基本查询语句 Select [distinc ...
随机推荐
- HTML Imports & deprecated
HTML Imports & deprecated https://caniuse.com/#search=html imports https://www.chromestatus.com/ ...
- c++ 使用PID获取可执行文件路径
注意看备注 https://docs.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-getmodulefilenameexa #includ ...
- js generator和yield
function co<T>(fn: () => Generator<any, any, any>): Promise<T> { const g: Gener ...
- NGK公链全面服务旅游经济
有数据显示,2019 年全球旅游总收入已达 6.5万亿美元, 占全球 GDP 的 7.3%,旅游业发展所创造的收益,于全球经济的重要性,不言而喻. 在旅游产业蓬勃发展的同时,中心化运营模式下却仍存在痛 ...
- C++算法模板集合
我的常用刷题网站:http://218.5.5.242:9018/JudgeOnline/ https://www.luogu.com.cn/ 排序 选择排序(selection sort) 1 vo ...
- Simple: SQLite3 中文结巴分词插件
一年前开发 simple 分词器,实现了微信在两篇文章中描述的,基于 SQLite 支持中文和拼音的搜索方案.具体背景参见这篇文章.项目发布后受到了一些朋友的关注,后续也发布了一些改进,提升了项目易用 ...
- Vue学习笔记-vue-element-admin 按装报错再按装
一 使用环境 开发系统: windows 后端IDE: PyCharm 前端IDE: VSCode 数据库: msyql,navicat 编程语言: python3.7 (Windows x86- ...
- Java基本概念:继承
一.简介 描述: 现实世界中的继承无处不在.比如:动物细分有哺乳动物.爬行动物等,哺乳动物细分有灵长目.鲸目等. 继承的本质是对某一批类的抽象,从而实现对现实世界更好的建模. 继承是类和类之间的一种关 ...
- 配置Nginx的坑及思路
我配置的是Django + uwsgi + Nginx 说下思路,先进行模块化测试: Django: Django 下 第一个坑是sql版本低问题,原因用pip安装不正确,在网上查了下按这个文章重装下 ...
- C#使用OpenCV剪切图像中的圆形和矩形
前言 本文主要介绍如何使用OpenCV剪切图像中的圆形和矩形. 准备工作 首先创建一个Wpf项目--WpfOpenCV,这里版本使用Framework4.7.2. 然后使用Nuget搜索[Emgu.C ...