1 view渲染

<form action="../src/website/import/report-flow" method="post" enctype="multipart/form-data">
</br>
type<input type="text" name="type" />
year<input type="text" name="year" />
month<input type="text" name="month" />
<input type="file" name="fileExcel" id="fileExcel" /> <br />
<input type="submit" name="submit" value="Submit" />
</form>

2 上传接口

src/modules/website/controllers/ImportController.php

    /**
* @author Anana
* 上传商销/盒 文件 异步处理
*/
public function actionReportFlow()
{
$uploadFile = UploadedFile::getInstanceByName ('fileExcel');
$type = intval(parent::getPostParam ('type')); // 文件上传类型
$year = intval(parent::getPostParam('year'));//年
$month = intval(parent::getPostParam('month'));//月
if($month<10){
$month = '0'.$month;
}
$accountRoleId= \Yii::$app->session['accountRoleRow']['account_role_id']; if(!in_array($type,array('1','2'))){
parent::apiReturn ( 1, [ ], '请先选择要上传的文件类型' );
}else if(!$year){
parent::apiReturn ( 1, [ ], '请选择年' );
}else if(!$month || $month > 12 ){
parent::apiReturn ( 1, [ ], '请选择月' );
}else if($uploadFile){
$fileExt = $uploadFile->getExtension (); // 文件后缀
$size = $uploadFile->size;//文件大小
if (! in_array ( $fileExt, array('xlsx','xls','csv') )) {
$reason [] = '上传的文件后缀名必须为xlsx、xls、csv';
}else if($size > 20*1024*1024){
$reason [] = '文件大小不能超过20M';
}else{
$fileName = date('Ymdhis').'_'.$accountRoleId;
if($type==1){
//商销/盒数据
$dir = 'report_flow_month';
}else {
//终端开户明细
$dir = 'open_accounts_month';
}
$fileName = $fileName.'.'.$fileExt;
$companyCode = \Yii::$app->session['companyRow']['code'];
$updateMonth =date('Y-m-00',strtotime("{$year}-{$month}"));
$buildsDir = dirname(\yii::$app->basePath)."/builds/{$companyCode}/{$dir}/$updateMonth";
//创建生成目录文件夹
if(!file_exists($buildsDir)){
mkdir($buildsDir,0777,true);
}
$csvPath = $buildsDir.'/'.$fileName;
$rs = $uploadFile->saveAs($csvPath);//文件另存为
if($rs){
$reportDaySalesFlowUploadLogModel = new ReportDaySalesFlowUploadLogModel();
$reportDaySalesFlowUploadLogModel->file_type = $type;
$reportDaySalesFlowUploadLogModel->role_id = $accountRoleId;
$reportDaySalesFlowUploadLogModel->new_file_name= $fileName;
$reportDaySalesFlowUploadLogModel->create_time = date("Y-m-d H:i:s");
$reportDaySalesFlowUploadLogModel->company = $companyCode;
$reportDaySalesFlowUploadLogModel->update_month = $updateMonth;
$rs = $reportDaySalesFlowUploadLogModel->insert();
if(!$rs){
parent::apiReturn ( 1, $jsonData, '上传日志更新失败' );
}
parent::apiReturn ( 0, [ ], '上传成功' );
}else{
$reason [] = '上传文件失败' . $uploadFile->error;
}
}
$jsonData = [ ];
if ($reason) {
$jsonData ['errorList'] = implode ( ' ', $reason );
parent::apiReturn ( 1, $jsonData, '错误信息提示' );
}
}else{
parent::apiReturn ( 1, [ ], '上传失败' );
}
}

3 上传以后处理数据

 /**
* 1 删除report_day_sales_flow_month表当月的老数据
* 2 插入report_day_sales_flow_month表当月新数据
*
*
* $fileName 文件名
* $fileLogId 文件id
*/
private function _updateReportDaySalesFlowMonth($fileName,$fileLogId,$updateMonth)
{
$connection = $this->_selectDb(); $buildsDir = dirname(\yii::$app->basePath)."/builds/yiling/xlsx/report_flow_month/$fileName";
if(!file_exists($buildsDir)){
echo "FILE NOT FOUND 找不到文件 \n ";
return;
}
$objReader = \PHPExcel_IOFactory::createReader('CSV');
$objReader->setReadDataOnly(true);// //只读去数据,忽略里面各种格式等(对于Excel读去,有很大优化)
$phpExcel = \PHPExcel_IOFactory::load ($buildsDir); // 自动判断Excel版本解析读取 $sheet = $phpExcel->getSheet ( 0 );
$collectionList = [ ]; // 初始化数据集合
$errorData = [ ]; // 导入的错误信息数据 有错误数据无法导入
$errorArray = [ ];
// 读取Excel数据行记录
$totalRow = $sheet->getHighestRow(); // 取得总行数 $thisTime = date("Y-m-d H:i:s");
for($i = 2; $i <= $totalRow; ++$i) {
$year = $sheet->getCellByColumnAndRow(0, $i)->getValue();
$month = $sheet->getCellByColumnAndRow(1, $i)->getValue();
$row['year_str'] = $year;
$row['month_str'] = $month;
$year_and_month = date("Y-m-00",strtotime(intval($year).'-'.intval($month)));
$row['update_month'] = $year_and_month;
$row['dept'] =$sheet->getCellByColumnAndRow(2, $i)->getValue();//部门
$row['business_dept'] =$sheet->getCellByColumnAndRow(3, $i)->getValue();//业务部门
$row['business_type'] =$sheet->getCellByColumnAndRow(4, $i)->getValue();//业务类型
$row['region_description'] =$sheet->getCellByColumnAndRow(5, $i)->getValue();//省区
$row['bussiness_region_description'] =$sheet->getCellByColumnAndRow(6, $i)->getValue();//业务省区
$row['region_named_code'] =$sheet->getCellByColumnAndRow(7, $i)->getValue();//区办代码
$row['region_named'] =$sheet->getCellByColumnAndRow(8, $i)->getValue();//区办
$row['parent_role_number'] =$sheet->getCellByColumnAndRow(9, $i)->getValue();//主管工号
$row['parent_role_name'] =$sheet->getCellByColumnAndRow(10, $i)->getValue();//主管姓名
$row['role_number'] =$sheet->getCellByColumnAndRow(11, $i)->getValue();//代表工号
$row['role_name'] =$sheet->getCellByColumnAndRow(12, $i)->getValue();//代表姓名
$row['client_number'] =$sheet->getCellByColumnAndRow(13, $i)->getValue();//终端代码
$row['client_name'] =$sheet->getCellByColumnAndRow(14, $i)->getValue();//终端名称
$row['province'] =$sheet->getCellByColumnAndRow(15, $i)->getValue();//省份
$row['city'] =$sheet->getCellByColumnAndRow(16, $i)->getValue();//城市
$row['district'] =$sheet->getCellByColumnAndRow(17, $i)->getValue();//区县
$row['hospital_type'] =$sheet->getCellByColumnAndRow(18, $i)->getValue();//医院类型
$row['custom_field_1'] =$sheet->getCellByColumnAndRow(19, $i)->getValue();//以岭级别
$row['nation_level'] =$sheet->getCellByColumnAndRow(20, $i)->getValue();//国家等级
$row['contract_type'] =$sheet->getCellByColumnAndRow(21, $i)->getValue();//承包类型
$row['custom_field_2'] =$sheet->getCellByColumnAndRow(22, $i)->getValue();//管理级别1
$row['group_name'] =$sheet->getCellByColumnAndRow(23, $i)->getValue();//品种
$row['goods_number'] =$sheet->getCellByColumnAndRow(24, $i)->getValue();//产品代码
$row['goods_name_spec'] =$sheet->getCellByColumnAndRow(25, $i)->getValue();//产品名称与品规
$row['purchase'] =$sheet->getCellByColumnAndRow(26, $i)->getValue();//商销/盒
$row['create_time'] =$thisTime;//导入时间
$row['file_log_id'] =$fileLogId;
$data[] = $row;
}
//释放内存
$sheet = $phpExcel =$phpExcel= null;
$fields = [
'year_str',
'month_str',
'update_month',
'dept',
'business_dept',
'business_type',
'region_description',
'bussiness_region_description',
'region_named_code',
'region_named',
'parent_role_number',
'parent_role_name',
'role_number',
'role_name',
'client_number',
'client_name',
'province',
'city',
'district',
'hospital_type',
'custom_field_1',
'nation_level',
'contract_type',
'custom_field_2',
'group_name',
'goods_number',
'goods_name_spec',
'purchase',
'create_time',
'file_log_id'
];
$rs = $connection->createCommand()->batchInsert('report_day_sales_flow_month',$fields,$data)->execute();
return $rs;
}

4 同步上传

    /**
* @author Anana
* http://localhost/src/website/import/region-named
* 上传以岭区办
*/
public function actionRegionNamed()
{
$uploadFile = UploadedFile::getInstanceByName ('fileExcel');
if(!$uploadFile){
parent::apiReturn ( 1, [ ], '上传失败' );
}
$fileExt = $uploadFile->getExtension (); // 文件后缀
$size = $uploadFile->size;//文件大小
if (! in_array ( $fileExt, array('xlsx','xls','csv') )) {
parent::apiReturn ( 1, [ ], '上传的文件后缀名必须为xlsx、xls、csv' );
}
if($size > 20*1024*1024){
parent::apiReturn ( 1, [ ], '文件大小不能超过20M' );
}
$objReader = \PHPExcel_IOFactory::createReader('CSV');
$objReader->setReadDataOnly(true);// //只读去数据,忽略里面各种格式等(对于Excel读去,有很大优化)
$phpExcel = \PHPExcel_IOFactory::load ( $uploadFile->tempName ); // 自动判断Excel版本解析读取
$sheet = $phpExcel->getSheet ( 0 );
$collectionList = [ ]; // 初始化数据集合 // 读取Excel数据行记录
$totalRow = $sheet->getHighestRow (); // 取得总行数 //所有部门
$deptArr = array(
1 => '医院一部',
2 => '医院二部',
3 => '社区部',
4 => '城乡部'
);
$deptFlipArr = array_flip($deptArr);
//所有业务部门
$bussinessDeptArr = array(
1=>'医院一部',
2=>'肿瘤产品部',
3=>'医院二部',
4 =>'社区部',
5 =>'城乡部',
6=>'城乡二部'
);
$bussinessDeptFlipArr = array_flip($bussinessDeptArr); //所有省区
$regionArea = RegionAreaModel::find()->select(['region_area_id','name'])->where(['is_valid'=>VALID])->asArray()->all();
foreach ($regionArea as $v){
$regionAreaArr[$v['region_area_id']] = $v['name'];
}
$regionAreaFlipArr = array_flip($regionAreaArr); //所有业务省区
$bussinessProvince = BussinessProvinceModel::find()->select(['bussiness_province_id','bussiness_province'])->where(['is_valid'=>VALID])->asArray()->all();
foreach ($bussinessProvince as $v){
$bussinessProvinceArr[$v['bussiness_province_id']] = $v['bussiness_province'];
}
$bussinessProvinceFlipArr = array_flip($bussinessProvinceArr); $hasError = False;
$roleId = \Yii::$app->session['accountRoleRow']['account_role_id'];
$thisTime = date("Y-m-d H:i:s"); // 跳过标题行
for($i = 2; $i <= $totalRow; ++ $i) {
$error = array();
$dept = trim ( $sheet->getCellByColumnAndRow ( 0, $i )->getValue () ); // 部门
$bussinessDept = trim ( $sheet->getCellByColumnAndRow ( 1, $i )->getValue () ); //业务部门
$regionArea = trim ( $sheet->getCellByColumnAndRow ( 2, $i )->getValue () ); //省区
$bussinessProvince = trim ( $sheet->getCellByColumnAndRow ( 3, $i )->getValue () ); //业务省区
$regionNamedCode = trim ( $sheet->getCellByColumnAndRow ( 4, $i )->getValue () ); //区办代码
$regionNamed = trim ( $sheet->getCellByColumnAndRow ( 5, $i )->getValue () ); //区办 if(!in_array($dept,$deptArr)){
$hasError = $hasError | true;
$error[] = '【部门】不存在 ';
}else{
$row['dept_id'] = $deptFlipArr[$dept];
}
if(!in_array($bussinessDept,$bussinessDeptArr)){
$hasError = $hasError | true;
$error[] = '【业务部门】不存在 ';
}else{
$row['bussiness_dept_id'] = $bussinessDeptFlipArr[$bussinessDept];
}
if(!in_array($regionArea,$regionAreaArr)){
$hasError = $hasError | true;
$error[] = '【省区】不存在 ';
}else{
$row['region_area_id'] = $regionAreaFlipArr[$regionArea];
} if(!in_array($bussinessProvince,$bussinessProvinceArr)){
$hasError = $hasError | true;
$error[] = '【业务省区】不存在 ';
}else{
$row['bussiness_province_id'] = $bussinessProvinceFlipArr[$bussinessProvince];
} if(mb_strlen($regionNamedCode)>20){
$hasError = $hasError | true;
$error[] = '【区办代码】太长了';
}
if(!$regionNamed || mb_strlen($regionNamed)>20){
$hasError = $hasError | true;
$error[] = '【区办】未填或太长了';
}else{
$regionNamedOne = RegionNamedModel::find()->select(['region_named_id'])->where(['region_named'=>$regionNamed, 'is_valid'=>VALID])->one();
if($regionNamedOne){
$hasError = $hasError | true;
$error[] = '此【区办】已存在,不可重复添加';
}
}
//$row['dept'] =$dept;
//$row['bussiness_dept']=$bussinessDept;
//$row['region_area'] = $regionArea;
//$row['bussiness_province'] = $bussinessProvince;
$row['region_named_code'] =$regionNamedCode;
$row['region_named'] = $regionNamed; $row['role_id'] = $roleId;
$row['create_time'] = $thisTime; if(isset($error) && $error ){
$row['error'] = implode(':',$error);
$sheet->setCellValueExplicitByColumnAndRow ( 6, $i,$row['error']);
}
$collectionList[] = $row;
} $fileName = 'region_named_error';
$fileName = $fileName.'.xlsx';
$companyCode = \Yii::$app->session['companyRow']['code'];
$buildsDir = dirname(\yii::$app->basePath)."/builds/{$companyCode}/region_named_error";
//创建生成目录文件夹
if(!file_exists($buildsDir)){
mkdir($buildsDir,0777,true);
}
$csvPath = $buildsDir.'/'.$fileName; //释放内存
$bussinessDeptFlipArr = $bussinessDeptArr = $bussinessProvinceFlipArr=$bussinessProvinceArr = null; //上传数据正确 插入数据表
if($hasError){
//释放内存
$collectionList = null;
//上传数据错误,写入文件
$phpExcelWriter = \PHPExcel_IOFactory::createWriter ( $phpExcel, 'Excel5' );
$rs = $phpExcelWriter->save ( $csvPath );
//$rs = $uploadFile->saveAs($csvPath);//文件另存为
parent::apiReturn ( 1, [ ], '上传数据有错误,已生成错误数据文件,请下载并按提示修改' );
}else{ //释放内存
$phpExcel = null;
\Yii::$app->params ['dbSelect'] = 'company'; // 切换到 company 数据库
\Yii::$app->params ['dsnSelect'] = 51;//yiling
$connection = \Yii::$app->companydb;
//$queryBuilder = $connection->queryBuilder;
$fields = ['dept_id','bussiness_dept_id','region_area_id','bussiness_province_id','region_named_code','region_named','role_id','create_time'];
$rs = $connection ->createCommand()->batchInsert(RegionNamedModel::tableName(),$fields, $collectionList)->execute();
if($rs){
//删除错误文件
unlink($csvPath);
parent::apiReturn ( 0, [ ], '导入数据成功' );
}
parent::apiReturn ( 1, [ ], '导入数据失败,请联系程序员');
}
}

记一次yii2 上传文件的更多相关文章

  1. 记一次FTP上传文件总是超时的解决过程

    好久没写博,还是重拾记录一下吧. 背景:买了一个阿里云的云虚拟机用来搭建网站(起初不了解云虚拟主机和云服务器的区别,以为都是有SSH功能的,后来发现不是这样样子啊,云虚拟机就是FTP上传网页+MySQ ...

  2. 记一次flask上传文件返回200前端却504的问题

    前言 好久没写了, 主要是太忙了, 本篇记一下今天解决的一个问题吧, 耗了我大半天的时间才解决 问题 今天在调试代码时, 发现了一个诡异的问题, 我之前写了一个接口, 作用是接收上传的文件, 因为这个 ...

  3. Yii2 UploadedFile上传文件

    通过 UploadFile::getInstance($model, $attribute); UploadFile::getInstances($model, $attribute); Upload ...

  4. NSURLSession/NSURLConnection的上传文件方法(已做了更新)

    最好的学习方法就是 领悟 + 证悟. 此篇文章的理论基础主要是与HTTP网络通信协议相关.为集中精力,可以先把TCP/IP协议这些置之不理,也就是先只关注HTTP的请求和响应的结构.HTTP完整的原理 ...

  5. 上传文件 file upload 学习笔记

    这里我只会说说一些完成 file upload 的基础 API. 很多项目我们需要上传文件. 有简单的 input file, 有需要验证的,有需要压缩的(img),有需要分段的(video),有需要 ...

  6. 关于初学者上传文件到github的方法

    转:http://blog.csdn.net/steven6977/article/details/10567719 说来也惭愧,我是最近开始用github,小白一个,昨天研究了一个下午.终于可以上传 ...

  7. github上传文件

    说来也惭愧,我是最近开始用github,小白一个,昨天研究了一个下午.终于可以上传了,所以今天写点,一来分享是自己的一些经验,二来也是做个记录,万一哪天又不记得了:) 废话不多说,直接来,这次主要介绍 ...

  8. Html标签,file方式,上传文件

    恩,如果不记下来,记忆就会模糊掉. 希望自己下次看见这篇博客的时候,会解决掉疑问 ----------------------------------------------------------- ...

  9. 『网络の转载』关于初学者上传文件到github的方法

    说来也惭愧,我是最近开始用github,小白一个,昨天研究了一个下午.终于可以上传了,所以今天写点,一来分享是自己的一些经验,二来也是做个记录,万一哪天又不记得了:) 废话不多说,直接来,这次主要介绍 ...

随机推荐

  1. spring使用注解通过子类注入父类的私有变量

    方法一 通过 super.setBaseDao方法设置父类私有变量 父类 public class BaseServiceImpl {    private BaseDao baseDao; publ ...

  2. Wpf开源收集

    1,到底有哪些开源MVVM框架? 前面介绍了WPF的基本概念和一些相关知识,我们了解到开发WPF应用程序可以使用现成的框架和模式,最为合适的莫过于时下正热的MVVM模式,所以这里我们也列出针对MVVM ...

  3. linux中脚本在任意目录执行

    完成了一个脚本,find.sh 如果希望可以再linux系统中任何位置都可以执行该脚本,可以执行下面操作 1. chmod 775 find.sh 给该脚本增加可执行权限 2. export PATH ...

  4. 浏览器F12(开发者调试工具) 功能介绍

    调试时使用最多的功能页面是:元素(ELements).控制台(Console).源代码(Sources).网络(Network)等. 元素(Elements):用于查看或修改HTML元素的属性.CSS ...

  5. python_项目_ATM和购物商城的程序

    1 需求 模拟实现一个ATM + 购物商城程序 额度15000或自定义 实现购物商城,买东西加入购物车,调用信用卡接口结账 可以提现,手续费5% 支持多账户登录 支持账户间转账 记录每月日常消费流水 ...

  6. 2016310Exp5 MSF基础应用

    1. 实践目标 本实践目标是掌握metasploit的基本应用方式,重点常用的三种攻击方式的思路.具体需要完成: 1.1一个主动攻击实践,如ms08_067; (1分) 1.2 一个针对浏览器的攻击, ...

  7. linux中开启snmp协议

    1.安装软件#yum -y install net-snmp 2.修改配置文件#vim /etc/snmp/snmpd.conf确保snmpd.conf文件中包含以下绿色内容:com2sec notC ...

  8. 20175236 2018-2019-2 《Java程序设计》第六周学习总结

    教材学习内容总结 第七章 try :用于监听.将要被监听的代码(可能抛出异常的代码)放在try语句块之内,当try语句块内发生异常时,异常就被抛出. catch:用于捕获异常.catch用来捕获try ...

  9. Service Worker 离线无法缓存Post请求的问题解决

    许多非REST API甚至可以用于读取数据的POST请求:典型的例子是graphql.soap和其他rpcpapi.但是,Post请求不能在一个现成的渐进式Web应用程序中缓存和脱机使用.浏览器的缓存 ...

  10. vs2017安装和使用教程(详细)

    借鉴:https://blog.csdn.net/qq_36556893/article/details/79430133#一.官网下载