Commit 3e469472 authored by wanghao's avatar wanghao

1 项目中使用 easypoi ,实现 一对多功能导入。环境部署测试。

parent cea890c8
......@@ -67,6 +67,13 @@
<artifactId>artemis-http-client</artifactId>
<version>1.1.3</version>
</dependency>
<!--hutool工具类-->
<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.25</version>
</dependency>
</dependencies>
......@@ -86,6 +93,19 @@
<!--</executions>-->
<!--</plugin>-->
<!--2024-08-29 处理excel文件损坏问题-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<version>2.6</version>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
......
package com.zehong.web.controller.supervise;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import com.zehong.common.core.domain.entity.SysUser;
......@@ -8,10 +11,14 @@ import com.zehong.common.utils.SecurityUtils;
import com.zehong.common.utils.ServletUtils;
import com.zehong.framework.web.service.TokenService;
import com.zehong.system.domain.TDetectorUserCount;
import com.zehong.system.domain.vo.GasUserAndSafetyDeviceExportVo;
import com.zehong.system.domain.vo.GasUserAndSafetyDeviceVo;
import com.zehong.system.domain.vo.TDetectorUserInspectVo;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
......@@ -28,6 +35,9 @@ import com.zehong.system.domain.TDetectorUser;
import com.zehong.system.service.ITDetectorUserService;
import com.zehong.common.utils.poi.ExcelUtil;
import com.zehong.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
/**
* 燃气用户Controller
......@@ -43,6 +53,10 @@ public class TDetectorUserController extends BaseController
private ITDetectorUserService tDetectorUserService;
@Autowired
private TokenService tokenService;
@Autowired
Environment environment;
/**
* 查询燃气用户列表
*/
......@@ -244,4 +258,108 @@ public class TDetectorUserController extends BaseController
return util.exportExcel(list, "用户安检数据");
}
/**
* 模版下载
* @return r
*/
@GetMapping("/importTemplate")
public AjaxResult importTemplate()
{
ExcelUtil<GasUserAndSafetyDeviceExportVo> util = new ExcelUtil<>(GasUserAndSafetyDeviceExportVo.class);
return util.importTemplateExcel("燃气用户数据");
}
/**
* 文件导入
* @param file f
* @param updateSupport u
* @return r
* @throws Exception r
*/
@PostMapping("/importData")
public AjaxResult importData(MultipartFile file, boolean updateSupport, HttpServletResponse response) throws Exception
{
ExcelUtil<GasUserAndSafetyDeviceExportVo> util = new ExcelUtil<>(GasUserAndSafetyDeviceExportVo.class);
List<GasUserAndSafetyDeviceExportVo> XmbhList = util.importExcel(file.getInputStream());
String operName = SecurityUtils.getLoginUser().getUsername();
String message = tDetectorUserService.importEmployedPeopleInfo(XmbhList, updateSupport, operName,response);
return AjaxResult.success(message);
}
/**
* 自定义-模版下载
* @param response r
* @throws IOException i
*/
@GetMapping("/downloadTemplate")
public void downloadTemplate(HttpServletResponse response) throws IOException {
//判断是否是 windows环境,
String osName = System.getProperty("os.name").toLowerCase();
try {
File file;
//如果是本地或测试环境
if (osName.contains("windows")) {
String filePath = "importTemplate/燃气用户导入模版.xlsx";
//用来读取resources下的文件
Resource resource = new ClassPathResource(filePath);
file = resource.getFile();
} else {
file = ResourceUtils.getFile("/data/java/baseversion/importTemplate/燃气用户导入模版.xlsx");
}
// 获取文件名
String filename = file.getName();
// 获取文件后缀名
String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
// 将文件写入输入流
FileInputStream fileInputStream = new FileInputStream(file);
InputStream fis = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.setCharacterEncoding("UTF-8");
//Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存
//attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
// filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
// 告知浏览器文件的大小
response.addHeader("Content-Length", "" + file.length());
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
outputStream.write(buffer);
outputStream.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* 自定义模版的导入
* @param file
* @return
* @throws Exception
*/
@PostMapping("/importCustom")
public AjaxResult importData(MultipartFile file,boolean updateSupport) throws Exception {
List<GasUserAndSafetyDeviceExportVo> dataInfos = ExcelUtil.importExcel(file, 1, 2, GasUserAndSafetyDeviceExportVo.class);
for (GasUserAndSafetyDeviceExportVo dataInfo : dataInfos) {
System.out.println(dataInfo.getLinkman());
}
return AjaxResult.success();
}
}
......@@ -146,6 +146,13 @@
<version>1.4</version>
</dependency>
<!--easypoi 一对多导入导出 -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.2.0</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.zehong.common.utils.poi;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.zehong.common.annotation.Excel;
import com.zehong.common.annotation.Excel.ColumnType;
import com.zehong.common.annotation.Excel.Type;
......@@ -14,6 +17,7 @@ import com.zehong.common.utils.StringUtils;
import com.zehong.common.utils.file.FileTypeUtils;
import com.zehong.common.utils.file.ImageUtils;
import com.zehong.common.utils.reflect.ReflectUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
......@@ -21,6 +25,7 @@ import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.lang.reflect.Field;
......@@ -1192,6 +1197,47 @@ public class ExcelUtil<T>
} catch (Exception e) {
log.error("列隐藏失败", e);
}
}
/**
* 导入数据
* @param file
* @param titleRows 标题在第几行
* @param headerRows 表头在第几行
* @param clazz
* @param <T>
* @return
*/
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows,
Class<T> clazz) {
if (file == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
params.setNeedVerify(true);
ExcelImportResult<T> result = null;
try {
InputStream inputStream = file.getInputStream();
result = ExcelImportUtil.importExcelMore(inputStream, clazz, params);
} catch (NoSuchElementException e) {
// 日志记录错误
log.error(String.format("导入数据为空: %s", ExceptionUtils.getStackTrace(e)));
throw new RuntimeException("导入数据为空");
} catch (Exception e) {
// 日志记录错误
log.error(String.format("导入失败: %s", ExceptionUtils.getStackTrace(e)));
throw new RuntimeException("导入失败");
}
if (result == null) {
return null;
}
if (result.isVerifyFail()) {
// 如有需要,可以根据result.getFailWorkbook();获取到有错误的数据
throw new RuntimeException("校验出错");
}
return result.getList();
}
}
\ No newline at end of file
package com.zehong.system.domain;
import java.util.Date;
import cn.afterturn.easypoi.excel.annotation.Excel;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.zehong.common.annotation.Excel;
import com.zehong.common.core.domain.BaseEntity;
/**
......@@ -21,11 +22,10 @@ public class TGasuserSafetyDeviceInfo extends BaseEntity
private Long gasUserSafetyDeviceId;
/** 用户管理-燃气用户关联id */
@Excel(name = "用户管理-燃气用户关联id")
private Long relationGasuserId;
/** 关联设备类型 */
@Excel(name = "关联设备类型")
@Excel(name = "设备类型")
private String relationDeviceType;
/** 设备名称 */
......@@ -46,11 +46,10 @@ public class TGasuserSafetyDeviceInfo extends BaseEntity
/** 设备安装时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "设备安装时间", width = 30, dateFormat = "yyyy-MM-dd")
@Excel(name = "设备安装时间", width = 30,format="yyyy-MM-dd")
private Date deviceInstallTime;
/** 安装位置 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "安装位置")
private String deviceInstallPosition;
......
package com.zehong.system.domain.vo;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import com.zehong.system.domain.TGasuserSafetyDeviceInfo;
import java.util.List;
public class GasUserAndSafetyDeviceExportVo {
/** 用户账号 */
@Excel(name = "用户账号", needMerge = true)
private String username;
/** 用户名称 */
@Excel(name = "用户名称", needMerge = true)
private String nickName;
@Excel(name = "燃气类型", needMerge = true)
private String gasType;
/** 用户类型(1居民用户,2商业用户,3工业用户) */
@Excel(name = "用户类型", needMerge = true)
private String userType;
/**
* 所属企业名称
*/
@Excel(name = "所属单位", needMerge = true)
private String beyondEnterpriseName;
/**
* 居住区(村、庄)
*/
@Excel(name = "居住区(村、庄)", needMerge = true)
private String villageName;
/** 地址 */
@Excel(name = "地址", needMerge = true)
private String address;
/** 联系人 */
@Excel(name = "联系人", needMerge = true)
private String linkman;
/** 电话 */
@Excel(name = "电话", needMerge = true)
private String phone;
/** 邮箱 */
@Excel(name = "邮箱", needMerge = true)
private String email;
/** 备注 */
@Excel(name = "备注", needMerge = true)
private String remarks;
/** 安全装置信息 */
@ExcelCollection(name = "安全装置信息")
private List<TGasuserSafetyDeviceInfo> gasuserSafetyDeviceInfoList;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getGasType() {
return gasType;
}
public void setGasType(String gasType) {
this.gasType = gasType;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getBeyondEnterpriseName() {
return beyondEnterpriseName;
}
public void setBeyondEnterpriseName(String beyondEnterpriseName) {
this.beyondEnterpriseName = beyondEnterpriseName;
}
public String getVillageName() {
return villageName;
}
public void setVillageName(String villageName) {
this.villageName = villageName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLinkman() {
return linkman;
}
public void setLinkman(String linkman) {
this.linkman = linkman;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public List<TGasuserSafetyDeviceInfo> getGasuserSafetyDeviceInfoList() {
return gasuserSafetyDeviceInfoList;
}
public void setGasuserSafetyDeviceInfoList(List<TGasuserSafetyDeviceInfo> gasuserSafetyDeviceInfoList) {
this.gasuserSafetyDeviceInfoList = gasuserSafetyDeviceInfoList;
}
}
......@@ -5,10 +5,10 @@ import java.util.Map;
import com.zehong.system.domain.TDetectorUser;
import com.zehong.system.domain.TDetectorUserCount;
import com.zehong.system.domain.vo.GasUserAndSafetyDeviceVo;
import com.zehong.system.domain.vo.TDetectorUserInspectVo;
import com.zehong.system.domain.vo.TDetectorUserVO;
import com.zehong.system.domain.vo.TMassMarksDetectorUserVO;
import com.zehong.system.domain.TEmployedPeopleInfoError;
import com.zehong.system.domain.vo.*;
import javax.servlet.http.HttpServletResponse;
/**
* 燃气用户Service接口
......@@ -161,4 +161,16 @@ public interface ITDetectorUserService
* @return
*/
List<TDetectorUserInspectVo> getDetectorUserInspectInfo(TDetectorUserInspectVo inspectVo);
/**
* 导入企业信息
*
* @param XmbhList 用户数据列表
* @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据
* @param operName 操作用户
* @return 结果
*/
public String importEmployedPeopleInfo(List<GasUserAndSafetyDeviceExportVo> XmbhList, Boolean isUpdateSupport, String operName, HttpServletResponse response);
}
......@@ -9,6 +9,7 @@ import java.util.stream.Collectors;
import com.zehong.common.utils.DateUtils;
import com.zehong.system.domain.TDetectorUserCount;
import com.zehong.system.domain.TGasuserSafetyDeviceInfo;
import com.zehong.system.domain.vo.GasUserAndSafetyDeviceExportVo;
import com.zehong.system.domain.vo.GasUserAndSafetyDeviceVo;
import com.zehong.system.domain.vo.TDetectorUserInspectVo;
import com.zehong.system.domain.vo.TDetectorUserVO;
......@@ -23,6 +24,7 @@ import com.zehong.system.domain.TDetectorUser;
import com.zehong.system.service.ITDetectorUserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
/**
* 燃气用户Service业务层处理
......@@ -399,4 +401,23 @@ public class TDetectorUserServiceImpl implements ITDetectorUserService
public List<TDetectorUserInspectVo> getDetectorUserInspectInfo(TDetectorUserInspectVo inspectVo){
return tDetectorUserMapper.getDetectorUserInspectInfo(inspectVo);
}
/**
* 燃气用户导入
* @param XmbhList 用户数据列表
* @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据
* @param operName 操作用户
* @param response
* @return
*/
@Override
public String importEmployedPeopleInfo(List<GasUserAndSafetyDeviceExportVo> XmbhList, Boolean isUpdateSupport, String operName, HttpServletResponse response) {
if(XmbhList.size() > 0) {
for (GasUserAndSafetyDeviceExportVo gasUserAndSafetyDeviceExportVo : XmbhList) {
System.out.println(gasUserAndSafetyDeviceExportVo.getLinkman());
}
}
return null;
}
}
......@@ -128,4 +128,24 @@ export function updateUserAndSafetyDevice(data) {
method: 'post',
data: data
})
}
// 下载用户导入模板
export function importTemplate() {
return request({
url: '/supervise/user/importTemplate',
method: 'get'
})
}
// 下载用户导入模板 - 自定义的模版
export function downloadTemplate() {
return request({
url: '/supervise/user/downloadTemplate',
method: 'get',
responseType: 'blob'
})
}
\ No newline at end of file
......@@ -65,6 +65,15 @@
@click="handleExport"
>导出</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="info"
icon="el-icon-upload2"
size="mini"
@click="handleImport">导入</el-button>
</el-col>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
</el-row>
......@@ -466,6 +475,38 @@
@close="dialogcancelFun"
@getPath="getPath"
/>
<!-- 用户导入对话框 -->
<el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
<el-upload
ref="upload"
:limit="1"
accept=".xlsx, .xls"
:headers="upload.headers"
:action="upload.url + '?updateSupport=' + upload.updateSupport"
:disabled="upload.isUploading"
:on-progress="handleFileUploadProgress"
:on-success="handleFileSuccess"
:auto-upload="false"
drag
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip text-center" slot="tip">
<div class="el-upload__tip" slot="tip">
<el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
</div>
<span>仅允许导入xls、xlsx格式文件。</span>
<el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
</div>
</el-upload>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitFileForm">确 定</el-button>
<el-button @click="upload.open = false">取 消</el-button>
</div>
</el-dialog>
</div>
</template>
......@@ -473,10 +514,11 @@
import { listUser, getUser, delUser, addUser, updateUser,newExportUser,
getNoSelectSafetyDetailInfo,addSafetyDetailInfo,deleteSafetyDeviceInfo,
deleteSafetyDeviceListInfo,selectSafetyDeviceDetailInfo,
addUserAndSafetyDevice,updateUserAndSafetyDevice} from "@/api/regulation/user";
addUserAndSafetyDevice,updateUserAndSafetyDevice,importTemplate,downloadTemplate} from "@/api/regulation/user";
import { selectTEnterprise} from "@/api/regulation/supervise";
import { noPageListVillage} from "@/api/regulation/userManagement/village";
import GetPos from '@/components/GetPos';
import { getToken } from "@/utils/auth";
export default {
name: "User",
components: {
......@@ -484,6 +526,21 @@ export default {
},
data() {
return {
upload: {
// 是否显示弹出层(用户导入)
open: false,
// 弹出层标题(用户导入)
title: "",
// 是否禁用上传
isUploading: false,
// 是否更新已经存在的用户数据
updateSupport: 0,
// 设置上传的请求头部
headers: { Authorization: "Bearer " + getToken() },
// 上传的地址
url: process.env.VUE_APP_BASE_API + "/supervise/user/importCustom" // todo
},
relationImg: require('@/assets/project/relation.png'),
//下拉框数据
test:{},
......@@ -624,8 +681,63 @@ export default {
});
this.getNoPageListVillage();
},
methods: {
methods: {
// 提交上传文件
submitFileForm() {
this.$refs.upload.submit();
},
handleImport(){
this.upload.title = "燃气用户导入"; // todo
this.upload.open = true;
},
/** 下载模板操作 */
importTemplate() {
downloadTemplate().then((res) =>{
let blob = new Blob([res], {type: 'data:application/vnd.ms-excel;base64;charset=utf-8'});
let downloadElement = document.createElement('a');
let href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.href = href;
downloadElement.download = '燃气用户导入模版'+'.xlsx'; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
return true
})
},
// 文件上传处理中
handleFileUploadProgress(event,file,fileList) {
this.upload.isUploading = true;
},
// 文件上传成功处理
handleFileSuccess(response, file, fileList) {
this.upload.open = false;
this.upload.isUploading = false;
this.$refs.upload.clearFiles();
this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
this.getDataList();
// this.countImportError();
// //导入后 刷新 任职岗位字典数据
// this.peopleOccupationOptions = [];
// this.queryPeopleOccupationByGroupByMethod();
},
/**关联设备已经选中数据删除方法*/
deleteDataListilInfo(row,index){
const deviceIds = row.gasUserSafetyDeviceId;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment