参考博文:Java实现Excel数据导入数据库_java读取excel文件并导入数据库_柚几哥哥的博客-优快云博客
excel内容:
开始项目:
- 新建一个springboot项目,pom.xml中导入依赖:lombok、poi、mybatis-plus
- 项目分层:
- 总体分为两部分:mapper和pojo一起的连接数据库底层部分 + controller和service一起的上层与代码实现部分,中间会调用Utils中的类方法。 (config是swagger等工具的配置类,如果用postman的话就不用配置了。)
-
底层:新建数据库 + 应用mybatis进行连接(配置部分) mapper+pojo层+数据库创建
新建数据库:sqlyog中,新建数据库再新建数据表,字符集选择utf8m64
利用mybatis-plus进行连接(其实是java中的sqlyog):
注:数据库中几个表,下面操作进行几次,以一个实体类为例进行说明:
(1)pojo中新建Tbzbzs实体类:里面变量对应表中的字段
@Data //声明好变量,直接再添加这个注释就行,getset方法就不用写了
public class TbZbzs{
private static final long serialVersionUID = 1L;
private String id; // id
private String bm; // 部门
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private java.util.Date sbsj; // 上报时间
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private java.util.Date jssj; // 结束时间
@TableField("del_flag") //逻辑删除
private int delFlag;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField("create_time") //变量名字不同时,用这个映射数据库中的字段名字
private Date createTime; //创建时间
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField("update_time")
private Date updateTime; //更新时间
}
(2)mybatis连接:
A、Mapper层中新建TbZbzsMapper,继承父类,<>中写入对应的实体类(表)
@Mapper
@Repository
public interface TbZbzsMapper extends BaseMapper<TbZbzs> {
// int insertTbZbzsList(List<TbZbzs> list); //批量进行操作时,要在这声明方法
}
B、resource中新建mapper包,下面写入TbZbzsMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.vivi.test3.mapper.TbZbzsMapper"> //这里写入上面的Mapper类
<!-- <insert id="insertTbZbzsList" parameterType="java.util.List">-->//这里是上面方法的具体实现语句,
//当excel中有200行时,可以批量一次插入到数据库中(代码只能一行行的进行,要进行200次插入)
<!-- insert into tb_zbzs (-->
<!-- id,-->
<!-- bm,-->
<!-- sbsj,-->
<!-- jssj,-->
<!-- del_flag,-->
<!-- create_time,-->
<!-- update_time-->
<!-- ) VALUES-->
<!-- <foreach collection="list" item="item" separator=",">-->
<!-- (-->
<!-- #{item.id},-->
<!-- #{item.bm},-->
<!-- #{item.sbsj},-->
<!-- #{item.jssj},-->
<!-- #{item.delFlag},-->
<!-- #{item.createTime},-->
<!-- #{item.createTime}-->
<!-- )-->
<!-- </foreach>-->
<!-- </insert>-->
</mapper>
C、主应用里面指定Mapper扫描路径
D、在application.properties中连接数据库
# 配置数据源信息
# 配置数据源类型
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/guangda?characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
mybatis-plus.mapper-locations=classpath:mapper/*.xml
自此,mapper层、pojo层结束。
-
controller层+service层
controller层:接收http请求,测试的时候可用swagger或者postman,除这个请求外下面可以写更多,访问http://localhost:8080/excelProTbZbzs即可,可以实现将excel表传入到数据库中,并返回success。 代码主要实现部分是service层中的fileUploadService类中的importTprkxx(file)方法。
@RestController
public class HelloController {
@Resource
FileUploadService fileUploadService;
@PostMapping(value = "/excelProTbZbzs") //测试时选择post方式
public String excelProTbZbzs(@RequestParam("file") MultipartFile file){
try {
Map<String, Object> result = fileUploadService.importTprkxx(file);//主要实现接口
return result.get("state").equals(200) ? "SUCESS" : result.get("mete").toString();
} catch (RuntimeException e){
return "ERROR";
}
}
service层:接口类+实现类
接口类FileUploadService:
@Service
public interface FileUploadService {
Map<String,Object> importTprkxx(MultipartFile file);
}
实现类FileUploadServiceImpl:
里面先调用了工具类ImportExcelUtil的getListByExcel(file)方法(将excel数据存入List<List<Object>>中),再调用tbZbzsMapper.insert(tbZbzs)方法,把list中的数据一行行的存入到数据库中,这里也可以在mapper中直接用代码写入。
@Service
public class FileUploadServiceImpl implements FileUploadService {
@Resource
TbZbzsMapper tbZbzsMapper;
@Override
public Map<String,Object> importTprkxx(MultipartFile file){
Map<String,Object> resultMap = new HashMap<>();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List<TbZbzs> tbZbzsList = new ArrayList<>();
try {
//验证文件类型
if (!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xls")&&!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xlsx")){
resultMap.put("mete", "文件类型有误!请上传Excle文件");
throw new Exception("文件类型有误!请上传Excle文件");
}
log.info("FileUploadServiceImpl importTprkxx file.name: {}", file.getName());
//获取数据(go->util!!!!)
List<List<Object>> olist = ImportExcelUtil.getListByExcel(file.getInputStream(), file.getOriginalFilename());
resultMap.put("导入成功",200);
//封装数据
for (int i = 0; i < olist.size(); i++) {
List<Object> list = olist.get(i);
if (list.get(0) == "" || ("序号").equals(list.get(0))) {
continue;
}
TbZbzs tbZbzs = new TbZbzs();
// tbZbzs.setId(UUID.randomUUID().toString().replace("-", "").substring(0, 20));
//根据下标获取每一行的每一条数据
if (String.valueOf(list.get(1))==null||String.valueOf(list.get(1)).equals("")) {
resultMap.put("mete", "部门不能为空");
throw new Exception("部门不能为空");
}
tbZbzs.setBm(String.valueOf(list.get(1)));
if (String.valueOf(list.get(2))==null||String.valueOf(list.get(2)).equals("")) {
resultMap.put("mete", "导入失败,上报时间不能为空");
throw new Exception("导入失败,上报时间不能为空");
}
try {
tbZbzs.setSbsj(simpleDateFormat.parse(String.valueOf(list.get(2))));
}catch (ParseException e){
resultMap.put("mete","请填写正确的时间格式!");
throw new Exception("请填写正确的时间格式!");
}
if (String.valueOf(list.get(3))==null||String.valueOf(list.get(3)).equals("")) {
resultMap.put("mete", "导入失败,结束时间不能为空");
throw new Exception("导入失败,结束时间不能为空");
}
try {
tbZbzs.setJssj(simpleDateFormat.parse(String.valueOf(list.get(3))));
}catch (ParseException e){
resultMap.put("mete","请填写正确的时间格式!");
throw new Exception("请填写正确的时间格式!");
}
if (String.valueOf(list.get(4))==null||String.valueOf(list.get(4)).equals("")) {
resultMap.put("mete", "逻辑删除不能为空");
continue;
}
tbZbzs.setDelFlag(Integer.parseInt(String.valueOf(list.get(4))));
if (String.valueOf(list.get(5))==null||String.valueOf(list.get(5)).equals("")) {
resultMap.put("mete", "导入失败,创建时间不能为空");
throw new Exception("导入失败,创建时间不能为空");
}
try {
tbZbzs.setCreateTime(simpleDateFormat.parse(String.valueOf(list.get(5))));
}catch (ParseException e){
resultMap.put("mete","请填写正确的时间格式!");
throw new Exception("请填写正确的时间格式!");
}
tbZbzsList.add(tbZbzs);
}
int i = 0;
for (TbZbzs tbZbzs : tbZbzsList) {
i += tbZbzsMapper.insert(tbZbzs); //mybatis-plus insert 500hang-500ci
}
if (i != 0) {
resultMap.put("state", 200);
}else {
resultMap.put("mete","文档内无数据,请重新导入");
resultMap.put("state", 500);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
return resultMap;
}
}
}
工具类ImportExcelUtil:
public class ImportExcelUtil {
private final static String excel2003L =".xls"; //2003- 版本的excel
private final static String excel2007U =".xlsx"; //2007+ 版本的excel
/**
* 描述:获取IO流中的数据,组装成List<List<Object>>对象
* @param in,fileName
* @return
* @throws Exception
*/
public static List<List<Object>> getListByExcel(InputStream in, String fileName) throws Exception {
List<List<Object>> list = null;
//创建Excel工作薄
Workbook work = ImportExcelUtil.getWorkbook(in,fileName);
if(null == work){
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList<List<Object>>();
//遍历Excel中所有的sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if(sheet==null){continue;}
//遍历当前sheet中的所有行
for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum()+1; j++) {
row = sheet.getRow(j);
if(row==null||row.getFirstCellNum()==j){continue;}
//遍历所有的列
List<Object> li = new ArrayList<Object>();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
li.add(ImportExcelUtil.getCellValue(cell));
}
list.add(li);
}
}
// work.close();
return list;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
* @param inStr,fileName
* @return
* @throws Exception
*/
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;
}
/**
* 描述:对表格中数值进行格式化
* @param cell
* @return
*/
public static Object getCellValue(Cell cell){
Object value = null;
DecimalFormat df = new DecimalFormat("0"); //格式化number String字符
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
// DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字
if (cell!=null){
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if("General".equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
}
else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
value = sdf.format(cell.getDateCellValue());
}
else{
value = sdf.format(cell.getDateCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK:
value = "";
break;
default:
break;
}
}
return value;
}
}