实现通过配置json,新建表,即可通过接口进行导入excel数据
json文件:
{
"1": {
"table": "enterprise_in_out", //表名
"fields": [
{
"field": "name", //字段名
"name": "企业名称", //excel列名
"cell": 0 //excel列数
},
{
"field": "in_value",
"name": "当月进口金额",
"cell": 1
},
{
"field": "out_value",
"name": "当月出口金额",
"cell": 2
},
{
"field": "month",
"name": "月份",
"cell": 3
}
]
}
}
主要代码:
@PostMapping("/importExcel")
public ResultVO<Object> importExcel(@RequestParam("file") MultipartFile file,@RequestParam("type")String type) {
try {
Workbook wb = null;
try {
wb = new HSSFWorkbook(file.getInputStream());
}catch (OfficeXmlFileException e){
wb = new XSSFWorkbook(file.getInputStream());
}
Sheet sheet = wb.getSheetAt(0);
Row row = null;
ClassPathResource resource = new ClassPathResource("json/inOut.json");
String jsonStr = IoUtil.read(resource.getInputStream(), StandardCharsets.UTF_8);
Map<String, Object> json = JSONUtil.toBean(jsonStr, Map.class);
Map<String, Object> typeMap = (Map<String, Object>) json.get(type);
String table = typeMap.get("table").toString();
List<Map<String, Object>> fieldList = (List<Map<String, Object>>) typeMap.get("fields");
List<List<String>> valueList = new ArrayList<>();
List<String> fields = new LinkedList<>();
for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
//获取每一行数据
row = sheet.getRow(i);
List<String> value = new LinkedList<>();
for (Map<String, Object> cellMap : fieldList){
value.add(row.getCell((Integer) cellMap.get("cell")).toString());
if (i == 1){
fields.add(cellMap.get("field").toString());
}
}
valueList.add(value);
}
mapper.insertImport(table, fields, valueList);
} catch (Exception e) {
e.printStackTrace();
}
return ResultVO.success();
}
mapper:
@Insert(
"<script>" +
" INSERT INTO ${tableName}"+
"<foreach item='item' index='index' collection='nameList' open='(' separator=',' close=')'>" +
" ${item}"+
"</foreach>"+
" VALUES "+
"<foreach item='it' index='index' collection='valueList' separator=',' close=';'>" +
"<foreach item='its' index='index' collection='it' open='(' separator=',' close=')'>" +
" #{its}"+
"</foreach>"+
"</foreach>"+
"</script>")
void insertImport(@Param("tableName")String table, @Param("nameList")List<String> fields, @Param("valueList")List<List<String>> valueList);