html:
<input type="file" name="fileName1" id="fileName1"/>
<input type="button" id="sendToUser" value="提交" />
JS
$('#sendToUser').click(function () {
var $file1 = $("input[name='fileName1']").val();
if ($file1 == "") {
alert("请选择上传的目标文件! ")
return false;
}
var fileName1 = $file1.substring($file1.lastIndexOf(".") + 1).toLowerCase();
if(fileName1 != "xls" && fileName1 !="xlsx"){
alert("请选择Execl文件!");
return false;
}
var size1 = $("input[name='fileName1']")[0].files[0].size;
if (size1>104857600) {
alert("上传文件不能大于100M!");
return false;
}
boo1 = true;
var type = "file";
var formData = new FormData();
formData.append(type,$("#fileName1")[0].files[0]);
$.ajax({
type : "post",
url : zzu+"/roughnes/importByExcel",
data : formData,
processData : false,
contentType : false,
success : function(data){
if (data=="error") {
alert("文件提交失败!");
}else{
$("input[name='userUrl']").val(data);
alert("文件上传成功!");
}}
});
})
Controller
@PostMapping("importByExcel")
@ResponseBody
public String importByExcel(@RequestParam("file") MultipartFile file){
roughnesService.importByExcel(file);
return "success";
}
Service
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void importByExcel(MultipartFile file) {
Map<Integer, Map<Object,Object>> map = new HashMap<>();
try {
map = OfficeUtils.readExcelContentz(file);
} catch (Exception e) {
e.printStackTrace();
}
Roughnes roughnes = new Roughnes();
String classParamStr = roughnes.toString();
String finalStr = classParamStr.substring(classParamStr.indexOf("(") + 1)
.replace("=null", "")
.replace(")","")
.replace(" ", "");
System.out.println(finalStr);
String[] split = finalStr.split(",");
List<String> paramList = Arrays.asList(split);
ArrayList<Roughnes> roughnesList = new ArrayList<>();
map.forEach((key,val) -> {
Roughnes finalRoughnes = new Roughnes();
val.forEach((key1,val1) -> {
String keyStr = String.valueOf(key1);
String valStr = String.valueOf(val1);
if (StringUtils.isEmpty(keyStr) || StringUtils.isEmpty(valStr)) {
return;
}
if ("id".equals(keyStr)) {
valStr = "X-" + valStr;
}
if (paramList.contains(keyStr)) {
switch (keyStr) {
case "id" :
finalRoughnes.setId(valStr);
break;
case "angle":
finalRoughnes.setAngle(Double.valueOf(valStr));
break;
case "p1Roughness" :
finalRoughnes.setP1Roughness(Double.valueOf(valStr));
break;
case "p2Roughness":
finalRoughnes.setP2Roughness(Double.valueOf(valStr));
break;
case "p3Roughness" :
finalRoughnes.setP3Roughness(Double.valueOf(valStr));
break;
case "p4Roughness":
finalRoughnes.setP4Roughness(Double.valueOf(valStr));
break;
case "p5Roughness" :
finalRoughnes.setP5Roughness(Double.valueOf(valStr));
break;
case "averageRoughne":
finalRoughnes.setAverageRoughne(Double.valueOf(valStr));
break;
}
}
});
roughnesList.add(finalRoughnes);
});
roughnesList.removeIf(roughnes1 -> null == roughnes1.getId());
roughnesMapper.insertBatch(roughnesList);
}
Mapper
<insert id="insertBatch" parameterType="list">
insert into roughnes
(id, angle, p1_roughness, p2_roughness, p3_roughness, p4_roughness, p5_roughness,average_roughne)
values
<foreach collection="list" item="item" separator=",">
(#{item.id},#{item.angle},#{item.p1Roughness},#{item.p2Roughness},#{item.p3Roughness},#{item.p4Roughness},#{item.p5Roughness},#{item.averageRoughne})
</foreach>
</insert>
OfficeUtils
public class OfficeUtils {
protected static final Logger logger = LoggerFactory.getLogger(OfficeUtils.class);
public static Map<Integer, Map<Object, Object>> readExcelContentz(MultipartFile file) throws Exception {
Map<Integer, Map<Object, Object>> content = new HashMap<Integer, Map<Object, Object>>();
Workbook wb = getWb(file);
if (wb == null) {
throw new RuntimeException("文件上传失败");
}
Sheet sheet = wb.getSheetAt(0);
int rowNum = sheet.getLastRowNum();
Row row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
Row firstRowCell = sheet.getRow(0);
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
Map<Object, Object> cellValue = new HashMap<Object, Object>();
while (j < colNum) {
Object obj = getCellFormatValue(row.getCell(j));
StringBuilder str = new StringBuilder(String.valueOf(firstRowCell.getCell(j)));
int o = 0;
StringBuilder replaced = str;
while ((o = str.indexOf("_",o)) != -1) {
String replaceStr = String.valueOf(str.charAt(o + 1)).toUpperCase();
replaced = str.replace(o+1,o+2,replaceStr);
str.replace(o, o+1, "");
o+=1;
}
cellValue.put(replaced, obj);
j++;
}
content.put(i, cellValue);
}
return content;
}
private static Object getCellFormatValue(Cell cell) {
Object cellvalue = "";
if (cell != null) {
switch (cell.getCellTypeEnum()) {
case NUMERIC:
cellvalue = String.valueOf(cell.getNumericCellValue());
break;
case FORMULA: {
cellvalue = cell.getDateCellValue();
break;
}
case STRING:
cellvalue = cell.getRichStringCellValue().getString();
break;
default:
cellvalue = "";
}
} else {
cellvalue = "";
}
return cellvalue;
}
private static Workbook getWb(MultipartFile mf) {
String filepath = mf.getOriginalFilename();
String ext = filepath.substring(filepath.lastIndexOf("."));
Workbook wb = null;
try {
InputStream is = mf.getInputStream();
if (".xls".equals(ext)) {
wb = new HSSFWorkbook(is);
} else if (".xlsx".equals(ext)) {
wb = new XSSFWorkbook(is);
} else {
wb = null;
}
} catch (FileNotFoundException e) {
logger.error("FileNotFoundException", e);
} catch (IOException e) {
logger.error("IOException", e);
}
return wb;
}
}