/**
* 上传文件
*
* @param request
* @param response
* @return
*/
private ModelAndView importFile(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> module = new HashMap<String, Object>();
String returnJson = "";
try {
//设置request请求的文件上传格式
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//从multipartRequest中获取文件对象
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
if (file != null) {
//输入流
InputStream in = new ByteArrayInputStream(file.getBytes());
//获取文件名
String fileName = file.getOriginalFilename();
//上传Excel,并返回上传结果
String result = importExcel(fileName, in);
returnJson = result;
}
} catch (Exception e) {
returnJson = "文件导入失败,请确认!";
}
module.put("message", returnJson);
return new ModelAndView("importFile", module);
}
//上传Excel,并返回上传结果
private String importExcel(String fileName, InputStream in) {
Date currentTime = new Date();
StringBuilder sb = new StringBuilder();
try {
//获取文件类型
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
Workbook workbook = null;
if ("xls".equals(suffix)) {
// Excel2003之前的文件
workbook = new HSSFWorkbook(in);
}
if ("xlsx".equals(suffix)) {
// Excel2007
workbook = new XSSFWorkbook(in);
}
if (workbook != null) {
//获取excel中的第一个sheet对象
Sheet sheet = workbook.getSheetAt(0);
//获取excel中的信息
List<Map<String, Object>> infos = getExcelInfoList(sheet);
for (Map<String, Object> property: infos) {
String id = UtilCommon.getString(property.get("id"));
String name = UtilCommon.getString(property.get("name"));
String age = UtilCommon.getString(property.get("age"));
String sex = UtilCommon.getString(property.get("sex"));
try {
Student student = new Student();
student.setId(id);
student.setName(name);
student.setAge(age);
student.setSex(sex);
studentService.saveOrUpdate(student);
} catch (Exception e) {
e.printStackTrace();
sb.append("create student failed:" + property + "</br>");
log.info("create student failed:" + property);
}
}
}
if (sb.length() == 0) {
sb.append("success");
}
} catch (Exception e) {
sb.append("import excel failed:" + e.getMessage() + "</br>");
log.info("import file failed[" + fileName + "]");
log.info(e.getMessage());
}
return sb.toString();
}
/**
* 获得EXCEL信息
*
* @param sheet
* @return
*/
private List<Map<String, Object>> getExcelInfoList(Sheet sheet) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
List<String> header = new ArrayList<String>();
//从第一行到最后一行依次获取
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
Row row = sheet.getRow(j);
if (j == sheet.getFirstRowNum()) {
// 默认Excel表起始行为表头信息
// 包装Excel的表头信息
header = getExcelHeaderList(row);
continue;
}
if (row != null) {
// 获得一行中的每列信息
Map<String, Object> map = new HashMap<String, Object>();
// 从Excel表的第一列开始读取信息
for (int k = 0; k < header.size(); k++) {
Cell cell = row.getCell(k);
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
double numeric = cell.getNumericCellValue();
map.put(header.get(k), numeric);
break;
case Cell.CELL_TYPE_BOOLEAN:
boolean b = cell.getBooleanCellValue();
map.put(header.get(k), b);
break;
case Cell.CELL_TYPE_STRING:
String value = cell.getStringCellValue();
map.put(header.get(k), UtilCommon.getString(value));
break;
default:
map.put(header.get(k), null);
break;
}
} else {
map.put(header.get(k), null);
}
}
list.add(map);
}
}
return list;
}
/**
* 获得student excel表头信息List
*
* @param row
* @return
*/
private List<String> getExcelHeaderList(Row row) {
List<String> header = new ArrayList<String>();
if (row != null) {
for (int i = 0; i < row.getLastCellNum(); i++) {
Cell cell = row.getCell(i);
if (cell != null) {
String value = UtilCommon.getString(cell.getStringCellValue());
if (!"".equals(value)) {
if ("学号".equals(value)) {
header.add(i, "id");
} else if ("姓名".equals(value)) {
header.add(i, "name");
} else if ("年龄".equals(value)) {
header.add(i, "age");
} else if ("性别".equals(value)) {
header.add(i, "sex");
} else {
header.add(i, null);
}
} else {
header.add(i, null);
}
} else {
header.add(i, null);
}
}
}
return header;
}
SpringMVC 实现文件上传
最新推荐文章于 2024-08-09 21:55:43 发布