我们需要把excel通过上传得方式导入数据库,需要以下几个步骤
- 将excel上传到服务器指定文件内并重命名(upload)
- 获取到文件公共路径和别名路径
- 将上传得文件转化成输入流(poi框架)
- 通过方法,将输入流文件数值转化成List
- >对象
- 遍历excel中得值,调用一次setFieldValueByFieldName方法,就对属性赋值一次,每次循环拿到一条数据,最终得到整个数据。
- 后台调用getObjectList(file, Exam.class)。
@PostMapping("/upload")
public ResultJson uploadFile(MultipartFile file ) throws Exception {
List
前天传过来得是二进制文件MultipartFile file
调用getObjectList方法(二进制文件,实体类对象)
package tech.niua.common.excelimport;
public class ObjectList {
public static List
package tech.niua.common.excelimport;
public class ExcelUtils {
private final static String excel2003L =".xls"; //2003- 版本的excel
private final static String excel2007U =".xlsx"; //2007+ 版本的excel
public static List> getListByExcel(InputStream in, String fileName) throws Exception{
List> list = null;
//创建Excel工作薄
Workbook work = getWorkbook(in,fileName);
if(null == work){
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null; //页数
Row row = null; //行数
Cell cell = null; //列数
list = new ArrayList>();
//遍历Excel中所有的sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
//取某个sheet
sheet = work.getSheetAt(i);
if(sheet==null){continue;}
//遍历当前sheet中的所有行
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
row = sheet.getRow(j);
if(row==null){continue;}
//遍历所有的列
List li = new ArrayList();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
li.add(getValue(cell));
}
list.add(li);
}
}
return list;
}
public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception{
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if(excel2003L.equals(fileType)){
wb = new HSSFWorkbook(inStr); //2003-
}else if(excel2007U.equals(fileType)){
wb = new XSSFWorkbook(inStr); //2007+
}else{
throw new Exception("解析的文件格式有误!");
}
return wb;
}
//解决excel类型问题,获得数值
public static String getValue(Cell cell) {
String value = "";
if(null==cell){
return value;
}
switch (cell.getCellType()) {
//数值型
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
//如果是date类型则 ,获取该cell的date值
Date date = DateUtil.getJavaDate(cell.getNumericCellValue());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
value = format.format(date);;
}else {// 纯数字
BigDecimal big=new BigDecimal(cell.getNumericCellValue());
value = big.toString();
//解决1234.0 去掉后面的.0
if(null!=value&&!"".equals(value.trim())){
String[] item = value.split("[.]");
if(1
三、导入成功



