模板文件导入与解析

master
lenovo 2 years ago
parent 9d78e9ea80
commit ed238a5881

@ -70,6 +70,17 @@
<version>3.5.2</version> <version>3.5.2</version>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.1.Final</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

@ -0,0 +1,64 @@
package com.gmh.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* redis
*
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/**
* valueJDK
*/
@Bean(name = "redisTemplateForJdkSerializer")
public RedisTemplate<Object, Object> redisTemplateForJdkSerializer(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
/**
* valueJson
*/
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(jackson2JsonRedisSerializer);
// Hash的key也采用StringRedisSerializer的序列化方式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}

@ -1,19 +1,28 @@
package com.gmh.controller; package com.gmh.controller;
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.GmhUser;
import com.gmh.entity.R; import com.gmh.entity.R;
import com.gmh.entity.RowCellNum;
import com.gmh.entity.SysBaijiaxing; import com.gmh.entity.SysBaijiaxing;
import com.gmh.entity.vo.ReadNameVo; import com.gmh.entity.vo.ReadNameVo;
import com.gmh.service.SysBaijiaxingService; import com.gmh.service.SysBaijiaxingService;
import com.gmh.utils.POIExcelUtil; import com.gmh.utils.POIExcelUtil;
import com.gmh.utils.RedisUtils;
import com.gmh.utils.RedisUtilsDefault;
import org.apache.poi.ss.usermodel.Cell;
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.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -22,10 +31,17 @@ import java.util.stream.Collectors;
@RequestMapping("/excel") @RequestMapping("/excel")
public class ExcelController { public class ExcelController {
public final ThreadLocal<Workbook> workbookThreadLocal = new ThreadLocal<>(); private Integer templateSheetNum = null;
private Workbook templateWorkbook = null;
private List<ReadNameVo> readNameVoList = null;
private static final String KEY_XINGMING = "姓名"; private static final String KEY_XINGMING = "姓名";
@Value("${gmh.upload-path}")
private String uploadPath;
@RequestMapping("/t01") @RequestMapping("/t01")
public R test01() { public R test01() {
return R.ok("ok"); return R.ok("ok");
@ -34,7 +50,7 @@ public class ExcelController {
@RequestMapping("/readData") @RequestMapping("/readData")
public R readSourceData(MultipartFile file) throws IOException { public R readSourceData(MultipartFile file) throws IOException {
Workbook workbook = POIExcelUtil.readExcelFromInputStream(file.getInputStream(), file.getOriginalFilename()); Workbook workbook = POIExcelUtil.readExcelFromInputStream(file.getInputStream(), file.getOriginalFilename());
List<ReadNameVo> resultList = new ArrayList<>(); readNameVoList = new ArrayList<>();
for (int i = 0; i < workbook.getNumberOfSheets(); i++) { for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
ReadNameVo readNameVo = new ReadNameVo(); ReadNameVo readNameVo = new ReadNameVo();
Sheet sheet = workbook.getSheetAt(i); Sheet sheet = workbook.getSheetAt(i);
@ -59,7 +75,7 @@ public class ExcelController {
for (Map<String, String> excelMap : excelMaps) { for (Map<String, String> excelMap : excelMaps) {
for (String key : excelMap.keySet()) { for (String key : excelMap.keySet()) {
String value = excelMap.get(key); String value = excelMap.get(key);
if (isChinaName(value)) { if (baijiaxingService.likeChineseName(value)) {
Integer count = map.getOrDefault(key, 0); Integer count = map.getOrDefault(key, 0);
map.put(key, ++count); map.put(key, ++count);
} }
@ -72,9 +88,10 @@ public class ExcelController {
readNameVo = getReadNameDataForNameKey(excelMaps, key); readNameVo = getReadNameDataForNameKey(excelMaps, key);
} }
readNameVo.setSheetName(sheet.getSheetName()); readNameVo.setSheetName(sheet.getSheetName());
resultList.add(readNameVo); readNameVoList.add(readNameVo);
} }
return R.ok().setData(resultList);
return R.ok().setData(readNameVoList);
} }
public ReadNameVo getReadNameDataForNameKey(List<Map<String, String>> excelMaps, final String key) { public ReadNameVo getReadNameDataForNameKey(List<Map<String, String>> excelMaps, final String key) {
@ -97,11 +114,90 @@ public class ExcelController {
} }
@RequestMapping("/template") @RequestMapping("/template")
public R templateUpload(MultipartFile file) 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());
List<Map<String, String>> maps = POIExcelUtil.toListMap(workbook.getSheetAt(0)); this.templateSheetNum = Integer.parseInt(templateSheetNum) - 1;
workbookThreadLocal.set(workbook); Sheet sheet = workbook.getSheetAt(this.templateSheetNum);
return R.ok().setData(maps); if (sheet == null) {
throw new RuntimeException("sheet页不存在");
}
this.templateWorkbook = workbook;
return R.ok();
}
@RequestMapping("/cellNumSearch")
public R analysisCell(String cellNum) {
String cellStrNum = cellNum.replaceAll("[^a-z^A-Z]", "");
String rowNum = cellNum.replaceAll("[^0-9]", "");
if (cellStrNum.length() > 2) {
return R.error(cellNum + "单元格不存在");
}
if (this.templateWorkbook == null) {
return R.error("模板文件出问题了,请重新上传");
}
Sheet sheet = this.templateWorkbook.getSheetAt(this.templateSheetNum);
Row row = sheet.getRow(Integer.parseInt(rowNum) - 1);
if (row == null) {
return R.error(cellNum + "单元格无内容");
}
int i = CellReference.convertColStringToIndex(cellStrNum);
Cell cell = row.getCell(i);
if (cell == null) {
return R.error(cellNum + "单元格无内容");
}
String stringCellVal = POIExcelUtil.getStringCellVal(cell);
if (StrUtil.isEmpty(stringCellVal)) {
return R.error(cellNum + "单元格无内容");
}
return R.ok().setData(stringCellVal);
}
public RowCellNum analysisCellNum(String cellNum) {
return null;
}
@RequestMapping("/executeTemplate")
public R executeTemplate(String newCellData) throws IOException {
System.out.println(newCellData);
String expr = newCellData.substring(newCellData.indexOf("@{"), newCellData.indexOf("}") + 1);
String exprVal = newCellData.substring(newCellData.indexOf("@{") + 2, newCellData.indexOf("}"));
String[] exprArr = exprVal.split("\\.");
String sheetName = exprArr[0];
String field = exprArr[1];
Optional<ReadNameVo> first = readNameVoList
.stream()
.filter(item -> item.getSheetName().equalsIgnoreCase(sheetName))
.findFirst();
if (!first.isPresent()) {
return R.error("未找到sheet页可能是表达式错误");
}
ReadNameVo readNameVo = first.get();
POIExcelUtil.removeModelSheet(this.templateWorkbook, sheetName);
POIExcelUtil.batchCloneSheet(this.templateWorkbook, this.templateSheetNum, readNameVo.getNameList().size());
ArrayList<GmhUser> gmhUsers = new ArrayList<>(readNameVo.getNameList());
for (int i = 0; i < this.templateWorkbook.getNumberOfSheets(); i++) {
Sheet sheet = templateWorkbook.getSheetAt(i);
if (sheet == null) {
continue;
}
Row row = sheet.getRow(2);
Cell cell = row.getCell(0);
cell.setCellValue(newCellData.replace(expr, gmhUsers.get(i).getName()));
}
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();
}
return R.ok();
} }
@Autowired @Autowired

@ -0,0 +1,11 @@
package com.gmh.entity;
import lombok.Data;
@Data
public class RowCellNum {
private Integer rowNum;
private Integer cellNum;
}

@ -4,4 +4,6 @@ import com.baomidou.mybatisplus.extension.service.IService;
import com.gmh.entity.SysBaijiaxing; import com.gmh.entity.SysBaijiaxing;
public interface SysBaijiaxingService extends IService<SysBaijiaxing> { public interface SysBaijiaxingService extends IService<SysBaijiaxing> {
boolean likeChineseName(String val);
} }

@ -1,11 +1,49 @@
package com.gmh.service.impl; package com.gmh.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gmh.dao.SysBaijiaxingDao; import com.gmh.dao.SysBaijiaxingDao;
import com.gmh.entity.SysBaijiaxing; import com.gmh.entity.SysBaijiaxing;
import com.gmh.service.SysBaijiaxingService; import com.gmh.service.SysBaijiaxingService;
import com.gmh.utils.RedisUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service @Service
public class SysBaijiaxingServiceImpl extends ServiceImpl<SysBaijiaxingDao, SysBaijiaxing> implements SysBaijiaxingService { public class SysBaijiaxingServiceImpl extends ServiceImpl<SysBaijiaxingDao, SysBaijiaxing> implements SysBaijiaxingService, InitializingBean {
@Autowired
private RedisUtils redisUtils;
@Override
public boolean likeChineseName(String val) {
if (StrUtil.isBlank(val)) {
return false;
}
String first = val.substring(0, 1);
Collection<String> keys = redisUtils.keys(KEY_XINGSHI + first + "*");
return keys.size() > 0;
// QueryWrapper<SysBaijiaxing> queryWrapper = new QueryWrapper<>();
// queryWrapper.apply("{0} LIKE CONCAT(xingshi,'%')", val);
// List<SysBaijiaxing> list = list(queryWrapper);
// return !list.isEmpty();
}
private static final String KEY_XINGSHI = "cache_xingshi:";
@Override
public void afterPropertiesSet() {
List<SysBaijiaxing> list = list();
Set<String> collect = list.stream().map(SysBaijiaxing::getXingshi).collect(Collectors.toSet());
for (String xingshi : collect) {
redisUtils.setCacheObject(KEY_XINGSHI + xingshi, xingshi);
}
}
} }

@ -208,4 +208,34 @@ public class POIExcelUtil {
} }
return list; return list;
} }
/**
* ( noDelSheet)
*/
public static void removeModelSheet(Workbook wb, Sheet noDelSheet) {
int sheetIndex = wb.getSheetIndex(noDelSheet);
removeModelSheet(wb,sheetIndex);
}
/**
* ( name)
*/
public static void removeModelSheet(Workbook wb, String name) {
int sheetIndex = wb.getSheetIndex(wb.getSheet(name));
removeModelSheet(wb,sheetIndex);
}
/**
* ( id)
*/
public static void removeModelSheet(Workbook wb, int id) {
int numberOfSheets = wb.getNumberOfSheets();
for (int i = numberOfSheets - 1; i > -1; i--) {
if (i != id) {
wb.removeSheetAt(i);
}
}
//设置默认显示第一页
wb.setActiveSheet(0);
}
} }

@ -0,0 +1,288 @@
package com.gmh.utils;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
/**
* spring redis
*
* @author callCenter
**/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisUtils {
@Autowired
public RedisTemplate redisTemplate;
/**
* IntegerString
*
* @param key
* @param value
*/
public <T> void setCacheObject(final String key, final T value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* IntegerString
*
* @param key
* @param value
* @param timeout
* @param timeUnit
*/
public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
/**
*
*
* @param key Redis
* @param timeout
* @return true=false=
*/
public boolean expire(final String key, final long timeout) {
return expire(key, timeout, TimeUnit.SECONDS);
}
/**
*
*
* @param key Redis
* @param timeout
* @param unit
* @return true=false=
*/
public boolean expire(final String key, final long timeout, final TimeUnit unit) {
return redisTemplate.expire(key, timeout, unit);
}
/**
*
*
* @param key
* @return
*/
public <T> T getCacheObject(final String key) {
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
/**
*
*
* @param key
*/
public boolean deleteObject(final String key) {
return redisTemplate.delete(key);
}
/**
*
*
* @param collection
* @return
*/
public long deleteObject(final Collection collection) {
return redisTemplate.delete(collection);
}
/**
* List
*
* @param key
* @param dataList List
* @return
*/
public <T> long setCacheList(final String key, final List<T> dataList) {
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
/**
* list
*
* @param key
* @return
*/
public <T> List<T> getCacheList(final String key) {
return redisTemplate.opsForList().range(key, 0, -1);
}
/**
* Set
*
* @param key
* @param dataSet
* @return
*/
public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
Iterator<T> it = dataSet.iterator();
while (it.hasNext()) {
setOperation.add(it.next());
}
return setOperation;
}
/**
* set
*
* @param key
* @return
*/
public <T> Set<T> getCacheSet(final String key) {
return redisTemplate.opsForSet().members(key);
}
/**
* Map
*
* @param key
* @param dataMap
*/
public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
/**
* Map
*
* @param key
* @return
*/
public <T> Map<String, T> getCacheMap(final String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* Hash
*
* @param key Redis
* @param hKey Hash
* @param value
*/
public <T> void setCacheMapValue(final String key, final String hKey, final T value) {
redisTemplate.opsForHash().put(key, hKey, value);
}
/**
* Hash
*
* @param key Redis
* @param hKey Hash
* @return Hash
*/
public <T> T getCacheMapValue(final String key, final String hKey) {
HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key, hKey);
}
/**
* Hash
*
* @param key
* @param hKey
*/
public void delCacheMapValue(final String key, final String hKey) {
HashOperations hashOperations = redisTemplate.opsForHash();
hashOperations.delete(key, hKey);
}
/**
* Hash
*
* @param key Redis
* @param hKeys Hash
* @return Hash
*/
public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
return redisTemplate.opsForHash().multiGet(key, hKeys);
}
/**
*
*
* @param pattern
* @return
*/
public Collection<String> keys(final String pattern) {
return redisTemplate.keys(pattern);
}
/**
* set
*
* @param key key
* @param value value
* @return
*/
public boolean setContains(String key, String value) {
Boolean member = redisTemplate.opsForSet().isMember(key, value);
if (member != null) {
return member;
}
return false;
}
/**
* key
*
* @param key
* @return
*/
public boolean hasKey(String key) {
Boolean hasKey = redisTemplate.hasKey(key);
if (hasKey == null) {
return false;
}
return hasKey;
}
/**
* key
*
* @param key
* @return
*/
public Long expireTime(String key) {
return redisTemplate.opsForValue().getOperations().getExpire(key);
}
/**
* Listsize
*
* @param key
* @return Listsize
*/
public <T> long getCacheListSisz(final String key) {
return redisTemplate.opsForList().size(key);
}
/**
* list
*
* @param key
* @return
*/
public <T> List<T> getCacheListRange(final String key, long start, long end) {
return redisTemplate.opsForList().range(key, start, end);
}
}

@ -0,0 +1,55 @@
package com.gmh.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* valuejdkredis
* pthink-plusredis value
*/
@Component
public class RedisUtilsDefault {
@Autowired
@Qualifier("redisTemplateForJdkSerializer")
public RedisTemplate redisTemplate;
/**
*
*
* @param key
* @return
*/
public <T> T getCacheObject(final String key) {
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
/**
* IntegerString
*
* @param key
* @param value
*/
public <T> void setCacheObject(final String key, final T value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* IntegerString
*
* @param key
* @param value
* @param timeout
* @param timeUnit
*/
public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
}

@ -3,3 +3,13 @@ spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/gmh?useSSL=false&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&serverTimezone=Asia/Shanghai spring.datasource.url=jdbc:mysql://localhost:3306/gmh?useSSL=false&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&serverTimezone=Asia/Shanghai
spring.datasource.username=root spring.datasource.username=root
spring.datasource.password=root spring.datasource.password=root
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database=6
gmh.upload-path="C:/develop/projUpload
#????????
spring.servlet.multipart.max-file-size=31457280
spring.servlet.multipart.max-request-size=31457280

Loading…
Cancel
Save