功能完善

master
lenovo 2 years ago
parent 12e5b2ccc6
commit d448628f55

@ -81,6 +81,12 @@
<version>6.0.1.Final</version> <version>6.0.1.Final</version>
</dependency> </dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

@ -0,0 +1,81 @@
package com.gmh.config;
import com.gmh.entity.FileEntity;
import com.gmh.entity.properties.FileServerProperties;
import com.gmh.service.impl.FileServiceImpl;
import com.gmh.utils.ThrowableUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
@Configuration
@ConditionalOnProperty(name = "data.file-server.type", havingValue = "local")
public class LocalFileAutoConfig {
private final Logger logger = LoggerFactory.getLogger(LocalFileAutoConfig.class);
@Autowired
private FileServerProperties fileProperties;
@Bean
public WebMvcConfigurer webMvcConfigurerAdapter() {
return new WebMvcConfigurer() {
/**
* 访
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(fileProperties.getLocal().getPrefix() + "/**")
.addResourceLocations(ResourceUtils.FILE_URL_PREFIX + fileProperties.getLocal().getPath() + File.separator);
}
};
}
@Service
public class LocalFileServiceImpl extends FileServiceImpl {
@Override
protected String fileType() {
return fileProperties.getType();
}
@Override
protected void uploadFile(MultipartFile file, FileEntity fileEntity) {
String localPath = fileProperties.getLocal().getPath();
File parentFile = new File(localPath);
if (!parentFile.exists()) {
if (!parentFile.mkdirs()) {
throw new RuntimeException("创建保存路径失败");
}
}
fileEntity.setFilePath(localPath + File.separator + fileEntity.getFileName());
File dest = new File(localPath + File.separator + fileEntity.getFileName());
try {
file.transferTo(dest);
} catch (IOException e) {
logger.error("全局异常信息ex={}, StackTrace={}", e.getMessage(), ThrowableUtil.getStackTrace(e));
}
}
@Override
protected void deleteFile(FileEntity fileEntity) {
File file = new File(fileEntity.getFilePath());
if (file.exists()) {
file.delete();
}
}
}
}

@ -1,31 +1,37 @@
package com.gmh.controller; package com.gmh.controller;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gmh.entity.GmhUser; import com.gmh.entity.*;
import com.gmh.entity.R; import com.gmh.entity.properties.FileServerProperties;
import com.gmh.entity.RowCellNum; import com.gmh.entity.query.ExecuteTemplateQuery;
import com.gmh.entity.SysBaijiaxing;
import com.gmh.entity.vo.ReadNameVo; import com.gmh.entity.vo.ReadNameVo;
import com.gmh.service.GmhFileLogService;
import com.gmh.service.FileService;
import com.gmh.service.SysBaijiaxingService; import com.gmh.service.SysBaijiaxingService;
import com.gmh.utils.CommonUtils; import com.gmh.utils.StringUtils;
import com.gmh.utils.POIExcelUtil; import com.gmh.utils.POIExcelUtil;
import com.gmh.utils.RedisUtils; import lombok.AllArgsConstructor;
import com.gmh.utils.RedisUtilsDefault; import lombok.Getter;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Pattern; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
@ -36,11 +42,19 @@ import java.util.stream.Collectors;
@RequestMapping("/excel") @RequestMapping("/excel")
public class ExcelController { public class ExcelController {
private Integer templateSheetNum = null; @Autowired
private FileService fileService;
@Autowired
private GmhFileLogService gmhFileLogService;
@Autowired
private FileServerProperties fileProperties;
private Workbook templateWorkbook = null; @Autowired
private SysBaijiaxingService baijiaxingService;
private List<ReadNameVo> readNameVoList = null; private final ExcelInfo excelInfo = new ExcelInfo();
private static final String KEY_XINGMING = "姓名"; private static final String KEY_XINGMING = "姓名";
@ -52,57 +66,68 @@ public class ExcelController {
return R.ok("ok"); return R.ok("ok");
} }
@RequestMapping("/readData") @RequestMapping("/dataSourceImport")
public R readSourceData(MultipartFile file) throws IOException { public R dataSourceImport(MultipartFile file, String dataSourceImportModel) throws IOException {
DataSourceImportModel importModel = DataSourceImportModel.findEnum(dataSourceImportModel);
Workbook workbook = POIExcelUtil.readExcelFromInputStream(file.getInputStream(), file.getOriginalFilename()); Workbook workbook = POIExcelUtil.readExcelFromInputStream(file.getInputStream(), file.getOriginalFilename());
readNameVoList = new ArrayList<>(); FileEntity fileEntity = fileService.uploadFile(file);
for (int i = 0; i < workbook.getNumberOfSheets(); i++) { gmhFileLogService.recordLog(fileEntity, GmhFileLog.OperateType.D_S_IMP);
ReadNameVo readNameVo = new ReadNameVo(); if (DataSourceImportModel.AUTO_NAME.equals(importModel)) {
Sheet sheet = workbook.getSheetAt(i); List<ReadNameVo> readNameVoList = new ArrayList<>();
List<Map<String, String>> excelMaps = POIExcelUtil.toListMap(sheet); for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
if (excelMaps.isEmpty()) { ReadNameVo readNameVo = new ReadNameVo();
continue; Sheet sheet = workbook.getSheetAt(i);
} List<Map<String, String>> excelMaps = POIExcelUtil.toListMap(sheet);
Map<String, String> firstElement = excelMaps.get(0); if (excelMaps.isEmpty()) {
String xmKey = KEY_XINGMING; continue;
for (String key : firstElement.keySet()) {
if (KEY_XINGMING.equals(firstElement.get(key))) {
xmKey = key;
} }
} Map<String, String> firstElement = excelMaps.get(0);
if (firstElement.containsKey(xmKey)) { String xmKey = KEY_XINGMING;
if (!KEY_XINGMING.equals(xmKey)) { for (String key : firstElement.keySet()) {
excelMaps.remove(firstElement); if (KEY_XINGMING.equals(firstElement.get(key))) {
xmKey = key;
}
} }
readNameVo = getReadNameDataForNameKey(excelMaps, xmKey); if (firstElement.containsKey(xmKey)) {
} else { if (!KEY_XINGMING.equals(xmKey)) {
Map<String, Integer> map = new HashMap<>(); excelMaps.remove(firstElement);
for (Map<String, String> excelMap : excelMaps) { }
for (String key : excelMap.keySet()) { readNameVo = getReadNameDataForNameKey(excelMaps, xmKey);
String value = excelMap.get(key); } else {
if (baijiaxingService.likeChineseName(value)) { Map<String, Integer> map = new HashMap<>();
Integer count = map.getOrDefault(key, 0); for (Map<String, String> excelMap : excelMaps) {
map.put(key, ++count); for (String key : excelMap.keySet()) {
String value = excelMap.get(key);
if (baijiaxingService.likeChineseName(value)) {
Integer count = map.getOrDefault(key, 0);
map.put(key, ++count);
}
} }
} }
} List<Map.Entry<String,Integer>> list = new ArrayList<>(map.entrySet());
List<Map.Entry<String,Integer>> list = new ArrayList<>(map.entrySet());
// list.sort(Comparator.comparingInt(Map.Entry::getValue)); //升序 // list.sort(Comparator.comparingInt(Map.Entry::getValue)); //升序
list.sort((o1, o2) -> (o2.getValue() - o1.getValue())); list.sort((o1, o2) -> (o2.getValue() - o1.getValue()));
String key = list.get(0).getKey(); String key = list.get(0).getKey();
readNameVo = getReadNameDataForNameKey(excelMaps, key); readNameVo = getReadNameDataForNameKey(excelMaps, key);
}
readNameVo.setSheetName(sheet.getSheetName());
readNameVoList.add(readNameVo);
} }
readNameVo.setSheetName(sheet.getSheetName()); excelInfo.setReadNameVoList(readNameVoList);
readNameVoList.add(readNameVo); return R.ok().setData(readNameVoList);
} }
return R.ok().setData(readNameVoList); return R.error();
} }
public ReadNameVo getReadNameDataForNameKey(List<Map<String, String>> excelMaps, final String key) { public ReadNameVo getReadNameDataForNameKey(List<Map<String, String>> excelMaps, final String key) {
ReadNameVo readNameVo = new ReadNameVo(); ReadNameVo readNameVo = new ReadNameVo();
// 去重前 // 去重前
List<GmhUser> oldNameList = excelMaps.stream().map(map -> new GmhUser(map.get(key))).collect(Collectors.toList()); List<GmhUser> oldNameList = excelMaps.stream()
.map(map -> new GmhUser(map.get(key)))
.filter(item -> StringUtils.isNotBlank(item.getName()))
.collect(Collectors.toList());
// 去重后 // 去重后
LinkedHashSet<GmhUser> newNameList = new LinkedHashSet<>(oldNameList); LinkedHashSet<GmhUser> newNameList = new LinkedHashSet<>(oldNameList);
readNameVo.setNameList(newNameList); readNameVo.setNameList(newNameList);
@ -118,24 +143,34 @@ public class ExcelController {
return readNameVo; return readNameVo;
} }
/**
*
* @param file excel
* @param templateSheetNum Sheet
* @return
* @throws IOException
*/
@RequestMapping("/template") @RequestMapping("/template")
public R templateUpload(MultipartFile file, String templateSheetNum) throws IOException { public R templateUpload(MultipartFile file, String templateSheetNum) throws IOException {
Workbook workbook = POIExcelUtil.readExcelFromInputStream(file.getInputStream(), file.getOriginalFilename()); Workbook workbook = POIExcelUtil.readExcelFromInputStream(file.getInputStream(), file.getOriginalFilename());
this.templateSheetNum = Integer.parseInt(templateSheetNum) - 1; FileEntity fileEntity = fileService.uploadFile(file);
Sheet sheet = workbook.getSheetAt(this.templateSheetNum); gmhFileLogService.recordLog(fileEntity, GmhFileLog.OperateType.TEMPL_IMP);
excelInfo.setTemplateOriginalFilename(file.getOriginalFilename());
excelInfo.setTemplateSheetNum(Integer.parseInt(templateSheetNum) - 1);
Sheet sheet = workbook.getSheetAt(excelInfo.getTemplateSheetNum());
if (sheet == null) { if (sheet == null) {
throw new RuntimeException("sheet页不存在"); throw new RuntimeException("sheet页不存在");
} }
this.templateWorkbook = workbook; excelInfo.setTemplateWorkbook(workbook);
return R.ok(); return R.ok();
} }
@RequestMapping("/cellNumSearch") @RequestMapping("/cellNumSearch")
public R analysisCell(@Validated RowCellNum rowCellNum) { public R analysisCell(@Validated RowCellNum rowCellNum) {
if (this.templateWorkbook == null) { if (excelInfo.getTemplateWorkbook() == null) {
return R.error("模板文件出问题了,请重新上传"); return R.error("模板文件出问题了,请重新上传");
} }
Sheet sheet = this.templateWorkbook.getSheetAt(this.templateSheetNum); Sheet sheet = excelInfo.getTemplateWorkbook().getSheetAt(excelInfo.getTemplateSheetNum());
rowCellNum = POIExcelUtil.analysisCellRowNum(rowCellNum); rowCellNum = POIExcelUtil.analysisCellRowNum(rowCellNum);
Row row = sheet.getRow(rowCellNum.getRowNum()); Row row = sheet.getRow(rowCellNum.getRowNum());
if (row == null) { if (row == null) {
@ -152,15 +187,17 @@ public class ExcelController {
return R.ok().setData(stringCellVal); return R.ok().setData(stringCellVal);
} }
@RequestMapping("/executeTemplate")
public void executeTemplate(String newCellData, String cellRowStr, HttpServletResponse response) throws IOException { @PostMapping("/executeTemplate")
public R executeTemplate(@RequestBody ExecuteTemplateQuery executeTemplateQuery) throws IOException {
String newCellData = executeTemplateQuery.getNewCellData();
String expr = newCellData.substring(newCellData.indexOf("@{"), newCellData.indexOf("}") + 1); String expr = newCellData.substring(newCellData.indexOf("@{"), newCellData.indexOf("}") + 1);
String exprVal = newCellData.substring(newCellData.indexOf("@{") + 2, newCellData.indexOf("}")); String exprVal = newCellData.substring(newCellData.indexOf("@{") + 2, newCellData.indexOf("}"));
String[] exprArr = exprVal.split("\\."); String[] exprArr = exprVal.split("\\.");
String sheetName = exprArr[0]; String sheetName = exprArr[0];
String field = exprArr[1]; String field = exprArr[1];
Optional<ReadNameVo> first = readNameVoList Optional<ReadNameVo> first = excelInfo.getReadNameVoList()
.stream() .stream()
.filter(item -> item.getSheetName().equalsIgnoreCase(sheetName)) .filter(item -> item.getSheetName().equalsIgnoreCase(sheetName))
.findFirst(); .findFirst();
@ -168,45 +205,77 @@ public class ExcelController {
throw new RuntimeException("未找到sheet页可能是表达式错误"); throw new RuntimeException("未找到sheet页可能是表达式错误");
} }
ReadNameVo readNameVo = first.get(); ReadNameVo readNameVo = first.get();
POIExcelUtil.removeModelSheet(this.templateWorkbook, this.templateSheetNum); POIExcelUtil.removeModelSheet(excelInfo.getTemplateWorkbook(), excelInfo.getTemplateSheetNum());
POIExcelUtil.batchCloneSheet(this.templateWorkbook, this.templateSheetNum, readNameVo.getNameList().size()); POIExcelUtil.batchCloneSheet(excelInfo.getTemplateWorkbook(), excelInfo.getTemplateSheetNum(), readNameVo.getNameList().size());
ArrayList<GmhUser> gmhUsers = new ArrayList<>(readNameVo.getNameList()); ArrayList<GmhUser> gmhUsers = new ArrayList<>(readNameVo.getNameList());
RowCellNum rowCellNum = POIExcelUtil.analysisCellRowNum(cellRowStr); RowCellNum rowCellNum = POIExcelUtil.analysisCellRowNum(executeTemplateQuery.getCellRowStr());
for (int i = 0; i < this.templateWorkbook.getNumberOfSheets(); i++) { for (int i = 0; i < excelInfo.getTemplateWorkbook().getNumberOfSheets(); i++) {
Sheet sheet = templateWorkbook.getSheetAt(i); Sheet sheet = excelInfo.getTemplateWorkbook().getSheetAt(i);
if (sheet == null) { if (sheet == null) {
continue; continue;
} }
Row row = sheet.getRow(rowCellNum.getRowNum()); Row row = sheet.getRow(rowCellNum.getRowNum());
Cell cell = row.getCell(rowCellNum.getCellNum()); Cell cell = row.getCell(rowCellNum.getCellNum());
cell.setCellValue(newCellData.replace(expr, CommonUtils.nameFormat(gmhUsers.get(i).getName()))); cell.setCellValue(newCellData.replace(expr, StringUtils.nameFormat(gmhUsers.get(i).getName())));
} }
// TODO 文件保存到本地,文件信息入库 // TODO 文件保存到本地,文件信息入库
String localPath = fileProperties.getLocal().getPath();
File parentFile = new File(localPath);
if (!parentFile.exists()) {
if (!parentFile.mkdirs()) {
throw new RuntimeException("创建保存路径失败");
}
}
FileEntity fileEntity = new FileEntity();
String extName = FileUtil.extName(excelInfo.getTemplateOriginalFilename());
String originalFilename;
if (StringUtils.isBlank(executeTemplateQuery.getResultExcelName())) {
originalFilename = excelInfo.getTemplateOriginalFilename();
} else {
originalFilename = executeTemplateQuery.getResultExcelName() + "." + extName;
}
fileEntity.setContentType(MediaType.ALL_VALUE)
.setOriginalFilename(originalFilename)
.setFileSize(2222L);
fileEntity.setFileType(fileProperties.getType());
String nowDate = DateUtil.format(new Date(), "yyyyMMddHHmmss");
fileEntity.setFileName(nowDate + "." + extName);
File dest = new File(localPath + File.separator + fileEntity.getFileName());
fileEntity.setFilePath(localPath + File.separator + fileEntity.getFileName());
FileOutputStream fout = null;
try {
fout = new FileOutputStream(dest);
excelInfo.getTemplateWorkbook().write(fout);
fileService.save(fileEntity);
gmhFileLogService.recordLog(fileEntity, GmhFileLog.OperateType.TEMPL_EXP);
} finally {
assert fout != null;
fout.close();
// excelInfo.getTemplateWorkbook().close();
}
return R.ok();
// 输出Excel文件 // 输出Excel文件 下载出去
OutputStream output = response.getOutputStream(); // OutputStream output = response.getOutputStream();
response.reset(); // response.reset();
// 设置文件头 // // 设置文件头
response.setHeader("Content-Disposition", // response.setHeader("Content-Disposition",
"attchement;filename=" + new String((sheetName + ".xls").getBytes("gb2312"), "ISO8859-1")); // "attchement;filename=" + new String((sheetName + ".xls").getBytes("gb2312"), "ISO8859-1"));
response.setContentType("application/msexcel"); // response.setContentType("application/msexcel");
this.templateWorkbook.write(output); // excelInfo.getTemplateWorkbook().write(fout);
this.templateWorkbook.close(); // excelInfo.getTemplateWorkbook().close();
// try {
// FileOutputStream out = new FileOutputStream("C:\\Users\\admin\\Desktop\\tempfile\\output\\out的222.xls");
// out.flush();
// templateWorkbook.write(out);
// out.close();
// System.out.println("文件输出完成");
// } catch (IOException e) {
// e.printStackTrace();
// }
} }
@Autowired @GetMapping("/gotoDownload")
private SysBaijiaxingService baijiaxingService; public R gotoDownload() {
try {
excelInfo.getTemplateWorkbook().close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return R.ok();
}
private boolean isChinaName(String val) { private boolean isChinaName(String val) {
QueryWrapper<SysBaijiaxing> queryWrapper = new QueryWrapper<>(); QueryWrapper<SysBaijiaxing> queryWrapper = new QueryWrapper<>();
@ -270,4 +339,27 @@ public class ExcelController {
// return R.ok().setData(readNameList); // return R.ok().setData(readNameList);
} }
/**
*
*/
@Getter
@AllArgsConstructor
public enum DataSourceImportModel {
AUTO_NAME("0", "自动识别姓名"),
ALL("1", "全部导入");
private final String value;
private final String remark;
public static DataSourceImportModel findEnum(String value) {
for (DataSourceImportModel item : values()) {
if (value.equals(item.getValue())) {
return item;
}
}
throw new RuntimeException("没有找到对应的枚举");
}
}
} }

@ -0,0 +1,9 @@
package com.gmh.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gmh.entity.GmhFileLog;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface GmhFileLogDao extends BaseMapper<GmhFileLog> {
}

@ -3,6 +3,7 @@ package com.gmh.entity;
import com.baomidou.mybatisplus.annotation.*; import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data; import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable; import java.io.Serializable;
import java.time.LocalDateTime; import java.time.LocalDateTime;

@ -0,0 +1,38 @@
package com.gmh.entity;
import com.gmh.entity.vo.ReadNameVo;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.ss.usermodel.Workbook;
import java.util.List;
@Getter
@Setter
public class ExcelInfo {
/**
* Sheet
*/
private Integer templateSheetNum;
/**
* workbook
*/
private Workbook templateWorkbook;
/**
*
*/
private List<ReadNameVo> readNameVoList;
/**
*
*/
private String templateOriginalFilename;
/**
*
*/
private Long size;
}

@ -0,0 +1,49 @@
package com.gmh.entity;
import com.gmh.controller.ExcelController;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
/**
*
*/
@Getter
@Setter
@Accessors(chain = true)
public class GmhFileLog extends BaseEntity{
/**
* id
*/
private String fileId;
/**
*
*/
private String operateType;
/**
*
*/
@Getter
@AllArgsConstructor
public enum OperateType {
D_S_IMP("0", "数据源导入"),
TEMPL_IMP("1", "模板导入"),
TEMPL_EXP("2", "模板导出");
private final String value;
private final String remark;
public static GmhFileLog.OperateType findEnum(String value) {
for (GmhFileLog.OperateType item : values()) {
if (value.equals(item.getValue())) {
return item;
}
}
throw new RuntimeException("没有找到对应的枚举");
}
}
}

@ -0,0 +1,28 @@
package com.gmh.entity.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "data.file-server")
public class FileServerProperties {
/**
* 4
* qiniuoss
* aliyunoss
* local
*/
private String type;
/**
* oss
*/
OssProperties oss = new OssProperties();
/**
* local
*/
LocalProperties local = new LocalProperties();
}

@ -0,0 +1,18 @@
package com.gmh.entity.properties;
import lombok.Data;
/**
*
*/
@Data
public class LocalProperties {
/**
*
*/
private String path;
/**
* url访
*/
private String prefix;
}

@ -0,0 +1,26 @@
package com.gmh.entity.properties;
import lombok.Data;
/**
* OSS
*/
@Data
public class OssProperties {
/**
* key
*/
private String accessKey;
/**
*
*/
private String accessKeySecret;
/**
*
*/
private String bucketName;
/**
* 访
*/
private String domainName;
}

@ -0,0 +1,24 @@
package com.gmh.entity.query;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ExecuteTemplateQuery {
/**
*
*/
private String newCellData;
/**
*
*/
private String cellRowStr;
/**
* Excel
*/
private String resultExcelName;
}

@ -1,9 +1,12 @@
package com.gmh.service; package com.gmh.service;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.gmh.entity.FileEntity; import com.gmh.entity.FileEntity;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.OutputStream;
public interface FileService extends IService<FileEntity> { public interface FileService extends IService<FileEntity> {
FileEntity uploadFile(MultipartFile file); FileEntity uploadFile(MultipartFile file);

@ -0,0 +1,10 @@
package com.gmh.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gmh.entity.GmhFileLog;
import com.gmh.entity.FileEntity;
public interface GmhFileLogService extends IService<GmhFileLog> {
void recordLog(FileEntity fileEntity, GmhFileLog.OperateType operateType);
}

@ -0,0 +1,73 @@
package com.gmh.service.impl;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gmh.dao.FileDao;
import com.gmh.entity.FileEntity;
import com.gmh.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public abstract class FileServiceImpl extends ServiceImpl<FileDao, FileEntity> implements FileService {
@Autowired
private FileDao fileDao;
@Override
public FileEntity uploadFile(MultipartFile file) {
FileEntity fileEntity = new FileEntity();
fileEntity.setContentType(file.getContentType())
.setOriginalFilename(file.getOriginalFilename())
.setFileSize(file.getSize());
String nowDate = DateUtil.format(new Date(), "yyyyMMddHHmmss");
String extName = FileUtil.extName(fileEntity.getOriginalFilename());
String fileName = nowDate + "." + extName;
fileEntity.setFileName(fileName);
uploadFile(file, fileEntity);
// 设置文件来源
fileEntity.setFileType(fileType());
// 将文件信息保存到数据库
fileDao.insert(fileEntity);
return fileEntity;
}
@Override
public void deleteFileById(String id) {
FileEntity fileEntity = fileDao.selectById(id);
if (fileEntity != null) {
fileDao.deleteById(fileEntity.getId());
deleteFile(fileEntity);
}
}
/**
*
*
* @return
*/
protected abstract String fileType();
/**
*
*
* @param file
* @param fileEntity
*/
protected abstract void uploadFile(MultipartFile file, FileEntity fileEntity);
/**
*
*
* @param fileEntity
* @return
*/
protected abstract void deleteFile(FileEntity fileEntity);
}

@ -0,0 +1,27 @@
package com.gmh.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gmh.dao.GmhFileLogDao;
import com.gmh.entity.GmhFileLog;
import com.gmh.entity.FileEntity;
import com.gmh.service.GmhFileLogService;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
@Service
public class GmhFileLogServiceImpl extends ServiceImpl<GmhFileLogDao, GmhFileLog> implements GmhFileLogService {
@Override
public void recordLog(FileEntity fileEntity, GmhFileLog.OperateType operateType) {
GmhFileLog gmhFileLog = new GmhFileLog();
gmhFileLog.setStatus("0");
gmhFileLog.setFileId(fileEntity.getId());
gmhFileLog.setCreateTime(LocalDateTime.now());
gmhFileLog.setCreateBy("gmh");
gmhFileLog.setUpdateTime(LocalDateTime.now());
gmhFileLog.setUpdateBy("gmh");
gmhFileLog.setOperateType(operateType.getValue());
save(gmhFileLog);
}
}

@ -1,23 +1,28 @@
package com.gmh.utils; package com.gmh.utils;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelFileUtil; import cn.hutool.poi.excel.ExcelFileUtil;
import com.gmh.entity.RowCellNum; import com.gmh.entity.RowCellNum;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference; import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.*; import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** /**
* POI Excel * POI Excel
* created on 2020/5/28 10:08
* *
* @author puhaiyang * @author Chenda
*/ */
public class POIExcelUtil { public class POIExcelUtil {
@ -34,48 +39,83 @@ public class POIExcelUtil {
} }
} }
public static Workbook cloneSheet(Workbook workbook, String srcSheetName, String destSheetName) { /**
* Sheet
*
* @param workbook workbook
* @param srcSheetName sheet
* @param newSheetName sheet
*/
public static void cloneSheet(Workbook workbook, String srcSheetName, String newSheetName) {
int index = workbook.getSheetIndex(srcSheetName); int index = workbook.getSheetIndex(srcSheetName);
return cloneSheet(workbook, index, destSheetName); cloneSheet(workbook, index, newSheetName);
} }
public static Workbook cloneSheet(Workbook workbook, Integer index, String destSheetName) { /**
* Sheet
*
* @param workbook workbook
* @param index sheet
* @param newSheetName sheet
*/
public static void cloneSheet(Workbook workbook, Integer index, String newSheetName) {
//克隆一个新的sheet //克隆一个新的sheet
Sheet newSheet = workbook.cloneSheet(index); Sheet newSheet = workbook.cloneSheet(index);
int sheetIndex = workbook.getSheetIndex(newSheet); int sheetIndex = workbook.getSheetIndex(newSheet);
workbook.setSheetName(sheetIndex, destSheetName); workbook.setSheetName(sheetIndex, newSheetName);
return workbook;
} }
public static Workbook cloneSheet(File excelFile, Integer index, String destSheetName) throws IOException { /**
* Sheet
*
* @param excelFile excel
* @param index sheet
* @param newSheetName sheet
* @throws IOException exception
*/
public static void cloneSheet(File excelFile, Integer index, String newSheetName) throws IOException {
Workbook workbook = readExcelFromFile(excelFile); Workbook workbook = readExcelFromFile(excelFile);
return cloneSheet(workbook, index, destSheetName); cloneSheet(workbook, index, newSheetName);
} }
/** /**
* sheet * sheet
* sheet1 2 3 4 ...
* *
* @param workbook workbook * @param workbook workbook
* @param index sheet * @param index sheet
* @param total sheet * @param total sheet
*/ */
public static Workbook batchCloneSheet(Workbook workbook, Integer index, Integer total) throws IOException { public static Workbook batchCloneSheet(Workbook workbook, Integer index, Integer total) {
// 将原始sheet重新命名防止复制出来的新sheet与它重名
workbook.setSheetName(index, RandomUtil.randomString(5));
for (int i = 0; i < total; i++) { for (int i = 0; i < total; i++) {
//克隆一个新的sheet cloneSheet(workbook, index, String.valueOf(i + 1));
Sheet newSheet = workbook.cloneSheet(index);
int sheetIndex = workbook.getSheetIndex(newSheet);
workbook.setSheetName(sheetIndex, String.valueOf(i + 1));
} }
workbook.removeSheetAt(index); workbook.removeSheetAt(index);
return workbook; return workbook;
} }
/**
* sheet
* sheet1 2 3 4 ...
*
* @param excelFile excel
* @param index sheet
* @param total sheet
*/
public static Workbook batchCloneSheet(File excelFile, Integer index, Integer total) throws IOException { public static Workbook batchCloneSheet(File excelFile, Integer index, Integer total) throws IOException {
Workbook workbook = readExcelFromFile(excelFile); Workbook workbook = readExcelFromFile(excelFile);
return batchCloneSheet(workbook, index, total); return batchCloneSheet(workbook, index, total);
} }
//读取excel /**
* excel
*
* @param file excel
* @return Workbook
* @throws IOException exception
*/
public static Workbook readExcelFromFile(File file) throws IOException { public static Workbook readExcelFromFile(File file) throws IOException {
if (file == null) { if (file == null) {
throw new RuntimeException("文件为空"); throw new RuntimeException("文件为空");
@ -83,10 +123,26 @@ public class POIExcelUtil {
return readExcelFromInputStream(Files.newInputStream(file.toPath()), file.getName()); return readExcelFromInputStream(Files.newInputStream(file.toPath()), file.getName());
} }
/**
* excel
*
* @param inputStream inputStream
* @return Workbook
* @throws IOException exception
*/
@Deprecated
public static Workbook readExcelFromInputStream(InputStream inputStream) throws IOException { public static Workbook readExcelFromInputStream(InputStream inputStream) throws IOException {
return readExcelFromInputStream(inputStream, null); return readExcelFromInputStream(inputStream, null);
} }
/**
* excel
*
* @param inputStream inputStream
* @param fileName
* @return Workbook
* @throws IOException exception
*/
public static Workbook readExcelFromInputStream(InputStream inputStream, String fileName) throws IOException { public static Workbook readExcelFromInputStream(InputStream inputStream, String fileName) throws IOException {
if (StrUtil.isNotBlank(fileName)) { if (StrUtil.isNotBlank(fileName)) {
String[] split = fileName.split("\\."); String[] split = fileName.split("\\.");
@ -111,10 +167,26 @@ public class POIExcelUtil {
} }
} }
/**
* excel
*
* - "张 叁" -> "张叁"
* - "麻花 " -> "麻花"
* - " 瑶 海 " -> "瑶海"
*
* @param cell cell
* @return cellValue
*/
public static String getStringCellValExcludeBlank(Cell cell) { public static String getStringCellValExcludeBlank(Cell cell) {
return getStringCellVal(cell).replaceAll("\\s*", ""); return getStringCellVal(cell).replaceAll("\\s*", "");
} }
/**
* excel
*
* @param cell cell
* @return cellValue
*/
public static String getStringCellVal(Cell cell) { public static String getStringCellVal(Cell cell) {
DataFormatter dataFormatter = new DataFormatter(); DataFormatter dataFormatter = new DataFormatter();
return dataFormatter.formatCellValue(cell); return dataFormatter.formatCellValue(cell);
@ -123,9 +195,9 @@ public class POIExcelUtil {
/** /**
* Excel List<Map<String, String>> * Excel List<Map<String, String>>
* *
* @param workbook workbook * @param workbook workbook
* @param sheetIndex sheet * @param sheetIndex sheet
* @return List<Map<String, String>> * @return List<Map < String, String>>
*/ */
public static List<Map<String, String>> toListMap(Workbook workbook, int sheetIndex) { public static List<Map<String, String>> toListMap(Workbook workbook, int sheetIndex) {
return toListMap(workbook, sheetIndex, -1); return toListMap(workbook, sheetIndex, -1);
@ -137,17 +209,17 @@ public class POIExcelUtil {
* @param workbook workbook * @param workbook workbook
* @param sheetIndex sheet * @param sheetIndex sheet
* @param titleRowNum <0 * @param titleRowNum <0
* @return List<Map<String, String>> * @return List<Map < String, String>>
*/ */
public static List<Map<String, String>> toListMap(Workbook workbook, int sheetIndex, int titleRowNum) { public static List<Map<String, String>> toListMap(Workbook workbook, int sheetIndex, int titleRowNum) {
return toListMap(workbook.getSheetAt(sheetIndex), titleRowNum); return toListMap(workbook.getSheetAt(sheetIndex), titleRowNum);
} }
/** /**
* Excel List<Map<String, String>> * Excel List<Map<String, String>>title
* *
* @param sheet workbook * @param sheet workbook
* @return List<Map<String, String>> * @return List<Map < String, String>>
*/ */
public static List<Map<String, String>> toListMap(Sheet sheet) { public static List<Map<String, String>> toListMap(Sheet sheet) {
return toListMap(sheet, -1); return toListMap(sheet, -1);
@ -156,9 +228,9 @@ public class POIExcelUtil {
/** /**
* Excel List<Map<String, String>> * Excel List<Map<String, String>>
* *
* @param sheet sheet * @param sheet sheet
* @param titleRowNum <0 * @param titleRowNum <0
* @return List<Map<String, String>> * @return List<Map < String, String>>
*/ */
public static List<Map<String, String>> toListMap(Sheet sheet, int titleRowNum) { public static List<Map<String, String>> toListMap(Sheet sheet, int titleRowNum) {
List<Map<String, String>> list = new ArrayList<>(); List<Map<String, String>> list = new ArrayList<>();
@ -215,7 +287,7 @@ public class POIExcelUtil {
*/ */
public static void removeModelSheet(Workbook wb, Sheet noDelSheet) { public static void removeModelSheet(Workbook wb, Sheet noDelSheet) {
int sheetIndex = wb.getSheetIndex(noDelSheet); int sheetIndex = wb.getSheetIndex(noDelSheet);
removeModelSheet(wb,sheetIndex); removeModelSheet(wb, sheetIndex);
} }
/** /**
@ -223,7 +295,7 @@ public class POIExcelUtil {
*/ */
public static void removeModelSheet(Workbook wb, String name) { public static void removeModelSheet(Workbook wb, String name) {
int sheetIndex = wb.getSheetIndex(wb.getSheet(name)); int sheetIndex = wb.getSheetIndex(wb.getSheet(name));
removeModelSheet(wb,sheetIndex); removeModelSheet(wb, sheetIndex);
} }
/** /**
@ -242,6 +314,7 @@ public class POIExcelUtil {
/** /**
* *
*
* @param cellRowStr A3 * @param cellRowStr A3
* @return * @return
*/ */
@ -251,6 +324,7 @@ public class POIExcelUtil {
/** /**
* *
*
* @param rowCellNum * @param rowCellNum
* @return * @return
*/ */

@ -1,6 +1,8 @@
package com.gmh.utils; package com.gmh.utils;
public class CommonUtils { import cn.hutool.core.util.StrUtil;
public class StringUtils extends StrUtil {
public static String nameFormat(String name) { public static String nameFormat(String name) {
StringBuilder newName = new StringBuilder(name.replaceAll("\\s*", "")); StringBuilder newName = new StringBuilder(name.replaceAll("\\s*", ""));

@ -0,0 +1,23 @@
package com.gmh.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ThrowableUtil {
/**
*
* @param throwable
* @return
*/
public static String getStackTrace(Throwable throwable){
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
throwable.printStackTrace(pw);
return sw.toString();
} finally {
pw.close();
}
}
}

@ -13,3 +13,13 @@ gmh.upload-path="C:/develop/projUpload
#???????? #????????
spring.servlet.multipart.max-file-size=31457280 spring.servlet.multipart.max-file-size=31457280
spring.servlet.multipart.max-request-size=31457280 spring.servlet.multipart.max-request-size=31457280
data.file-server.type: local
#oss??
data.file-server.oss.access-key: tpi8mObnfzZi4ggBX8Bw7zydjoTQ0WeML3RkPKsX
data.file-server.oss.access-key-secret: HZBXmSyUTy-haYp0KbBTtsil-GoKjVS2kDKT8Yow
data.file-server.oss.bucket-name: public-oss
data.file-server.oss.domain-name: http://pkqtmn0p1.bkt.clouddn.com
#local??
data.file-server.local.path: C:\\develop\\uploadfile
data.file-server.local.prefix: fileView
Loading…
Cancel
Save