1.调用类
2.service方法
@Override
public boolean addBatchByFile(MultipartFile file) {
try {
File foler = new File(filePath);
if (!foler.exists()) {
boolean f = foler.mkdirs();
if (!f) {
log.error("批量 foler.mkdirs failed,folder:" + foler.getAbsolutePath());
}
}
String fileNamePath = foler.getAbsolutePath() + File.separator + file.getOriginalFilename();
File dest = new File(fileNamePath);
if (!dest.exists()) {
boolean cf = dest.createNewFile();
if (cf) {
FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
}
} else {
log.error("批量补录 dest.createNewFile failed,folder:" + foler.getAbsolutePath());
}
List list = (List) ExcelUtils.getListByExcel(fileNamePath,TestEntity.class);
//删除文件
dest.delete();
//批量插入
if (list != null && list.size() > 0) {
testMapper.insertBatch(list);
return true;
} else {
return false;
}
} catch (Exception e) {
log.error("addBatchByFile fail", e);
return false;
}
}
3.工具类
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ExcelUtils {
public static List> getListByExcel(String path, Class> className) {
List> list = null;
// 文件类型
String filetype = path.substring(path.lastIndexOf("."));
// 读取excel文件
InputStream in = null;
// 获取工作簿
Workbook wb = null;
try {
in = new FileInputStream(path);
if (filetype.equals(".xls")) {
wb = new HSSFWorkbook(in);
} else if (filetype.equals(".xlsx")) {
wb = new XSSFWorkbook(in);
} else {
log.error("文件类型必须是xls或xlsx,file=" + path);
in.close();
return null;
}
// 获取第一个sheet集合
if (wb.getSheetAt(0) != null) {
list = getListBySheet(wb.getSheetAt(0), className);
}
in.close();
wb.close();
} catch (Exception e) {
log.error("读取文件失败" + path, e);
} finally {
try {
if (in != null) {
in.close();
}
if (wb != null) {
wb.close();
}
} catch (IOException e) {
log.error("关闭流失败" + path, e);
}
}
return list;
}
private static List> getListBySheet(Sheet sheet, Class> className) {
List
4.pom.xml
org.apache.poi
poi
4.1.2
org.apache.poi
poi-ooxml
4.1.2
org.apache.poi
poi-ooxml-schemas
4.1.2
org.apache.poi
poi-scratchpad
4.1.2
commons-io
commons-io
${commons.io.version}