把excel数据导入数据库之java实现

本人用的是springboot+gradle
话不多说,直接上干货:

package com.gpt.web.front.controller.content;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gpt.common.core.domain.AjaxResult;
import com.gpt.common.utils.SnowFlakeUtil;
import com.gpt.manage.domain.QCategorize;
import com.gpt.manage.domain.QConversation;
import com.gpt.manage.domain.QTemplate;
import com.gpt.manage.service.QCategorizeService;
import com.gpt.manage.service.QConversationService;
import com.gpt.manage.service.QTemplateService;
import com.gpt.web.front.utils.ImportExcelUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = {
    
    "导入数据库模板信息"})
@RestController
@RequestMapping("/importSql")
@Slf4j
public class ImportSqlController {
    
    
    /**
     * 导入数据库模板
     *
     * @author wangjj
     * @version 1.0
     * @date 2023/3/17 14:42
     */
    @Autowired
    private QTemplateService templateService;
    @Autowired
    private QCategorizeService categorizeService;

    @PostMapping(value = "/excelToSql")
    public AjaxResult excelProTbZbzs(@RequestParam("file") MultipartFile file) {
    
    
        List<QTemplate> template = new ArrayList<>();
        try {
    
    
            //验证文件类型
            if (!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xls") && !file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xlsx")) {
    
    
                AjaxResult.error("mete", "文件类型有误!请上传Excle文件");
                throw new Exception("文件类型有误!请上传Excle文件");
            }

            //获取数据
            List<List<Object>> olist = ImportExcelUtil.getListByExcel(file.getInputStream(), file.getOriginalFilename());

            //封装数据
            for (int i = 0; i < olist.size(); i++) {
    
    
                List<Object> list = olist.get(i);
                if (list.get(0) == "" || ("序号").equals(list.get(0))) {
    
    
                    continue;
                }
                QTemplate t = new QTemplate();

                //标题
                if (String.valueOf(list.get(0)) == null || String.valueOf(list.get(0)).equals("")) {
    
    
                    AjaxResult.error("TemplateTitle", "标题不能为空");
                    throw new Exception("标题不能为空");
                }
                t.setTemplateTitle(String.valueOf(list.get(0)));
                //内容
                if (String.valueOf(list.get(1)) == null || String.valueOf(list.get(1)).equals("")) {
    
    
                    AjaxResult.error("mete", "内容不能为空");
                    throw new Exception("TemplateContent不能为空");
                }
                t.setTemplateContent(String.valueOf(list.get(1)));

                //分类id
                if (StringUtils.isNotEmpty(String.valueOf(list.get(2)))) {
    
    
                    QCategorize categorize = categorizeService.getOne(new LambdaQueryWrapper<QCategorize>().eq(QCategorize::getName, String.valueOf(list.get(2))));
                    if (categorize != null) {
    
    
                        t.setCategorizeId(categorize.getId());
                    }
                }
                //分类内容
                if (String.valueOf(list.get(2)) == null || String.valueOf(list.get(2)).equals("")) {
    
    
                    AjaxResult.error("Categorize", "分类内容不能为空");
                    throw new Exception("分类内容不能为空");
                }
                t.setCategorize(String.valueOf(list.get(2)));
                t.setGrade(Integer.parseInt(String.valueOf(list.get(3))));
                t.setCreateDate(new Date());
                t.setUpdateDate(new Date());
                template.add(t);
            }
            templateService.insertListInfo(template);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return AjaxResult.success("插入数据库成功");
    }
}

工具类如下:

package com.gpt.web.front.utils;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 新增值班排班表导入Excel表工具类
 * zyw
 */
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 val = 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) {
    
    
            if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA) {
    
    
                val = cell.getNumericCellValue();
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
    
    
                    val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
                } else {
    
    
                    if ((Double) val % 1 > 0) {
    
    
                        val = new BigDecimal(val.toString());
                    } else {
    
    
                        val = new DecimalFormat("0").format(val);
                    }
                }
            } else if (cell.getCellTypeEnum() == CellType.STRING) {
    
    
                val = cell.getStringCellValue();
            } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
    
    
                val = cell.getBooleanCellValue();
            } else if (cell.getCellTypeEnum() == CellType.ERROR) {
    
    
                val = cell.getErrorCellValue();
            }
//            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 val;
    }
}

注意:需要导入POI需要的包

 compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.17'

猜你喜欢

转载自blog.csdn.net/leaning_java/article/details/129616534
今日推荐