springboot上傳excel表格到數據庫

  • 1.引入相關poi依賴
<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>${poi.version}</version>
        </dependency>
複製代碼
  • 2.寫出和數據庫對應的實體類
  • 3.編寫dao接口
@Mapper
@Service
public interface ExcelDao {

    void batchInsert(List<GmVipMember> gmVipMemberList);
}
複製代碼
    1. service
/**
 * 批量導入excel數據
 * @author BI
 * @date 2019/1/4 - 13:44
 */
public interface ExcelImportService {

    Integer importExcel(MultipartFile myFile);
}
複製代碼

serviceImplhtml

@Service
public class ExcelImportServiceImpl implements ExcelImportService {
    //定義excel的格式
    private final static String XLS = "xls";
    private final static String XLSX = "xlsx";

    private final static Logger logger = LoggerFactory.getLogger(ExcelImportServiceImpl.class);

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private ExcelDao excelDao;


    @Override
    public Integer importExcel(MultipartFile myFile) {
        //1.使用HSSFWorkbook 打開或者建立"Excel對象"
        //2.用HSSFWorkbook返回對象或者建立sheet對象
        //3.用sheet返回行對象,用行對象獲得Cell對象
        //4.對cell對象進行讀寫

        List<GmVipMember> gmVipMembers = new ArrayList<>();
        Workbook workbook = null;
        String fileName = myFile.getOriginalFilename();//獲取文件名
        logger.info("[fileName:{}", fileName);
        if (fileName.endsWith(XLS)) {
            try {
                workbook = new HSSFWorkbook(myFile.getInputStream());//2003版本
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (fileName.endsWith(XLSX)) {
            try {
                workbook = new XSSFWorkbook(myFile.getInputStream());//2007版本
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            throw new ExcelException(ResultEnum.FILE_IS_NOT_EXCEL); //文件不是Excel文件
        }

        Sheet sheet = workbook.getSheet("sheet1");
        int rows = sheet.getLastRowNum();
        int cells = sheet.getRow(0).getPhysicalNumberOfCells();
        String cell = sheet.getRow(0).getCell(0).getStringCellValue();


        logger.info("[rows]{}", rows);
        if (rows < 1) {
            throw new ExcelException(ResultEnum.DATA_IS_NULL); //數據爲空 請填寫數據
        } else if (!cell.equals("卡號")){
            throw new ExcelException(ResultEnum.FILE_IS_NOT_TRUEEXCEL); //文件格式不正確
        }

        long startTime = System.currentTimeMillis();
        for (int i = 1; i <= rows + 1; i++) {
            Row row = sheet.getRow(i);

            //從excel列中讀取數據並set給實體類
            if (row != null) {
                GmVipMember gm = new GmVipMember();

                //會員卡號
                String memId = getCellValue(row.getCell(0));
                gm.setMemId(memId);
                //真實姓名
                String realName = getCellValue(row.getCell(1));
                gm.setRealName(realName);

                String telNum = getCellValue(row.getCell(2));
                gm.setTelNum(telNum);

                String cid = getCellValue(row.getCell(3));
                gm.setCid(cid);

                String refereeTelNum = getCellValue(row.getCell(4));
                gm.setRefereeTelNum(refereeTelNum);

                String refereeName = getCellValue(row.getCell(5));
                gm.setRefereeName(refereeName);

                String integral = getCellValue(row.getCell(6));
                gm.setIntegral(integral);

                String birthday = getCellValue(row.getCell(7));
                gm.setBirthday(birthday);

                String nation = getCellValue(row.getCell(8));
                gm.setNation(nation);

                String education = getCellValue(row.getCell(9));
                gm.setEducation(education);

                String isMarry = getCellValue(row.getCell(10));
                gm.setIsMarry(isMarry);

                String sex = getCellValue(row.getCell(11));
                gm.setSex(sex);

                String cidAddress = getCellValue(row.getCell(12));
                gm.setCidAddress(cidAddress);

                String detaileAddress = getCellValue(row.getCell(13));
                gm.setDetaileAddress(detaileAddress);

                String groupNo = getCellValue(row.getCell(14));
                gm.setGroupNo(groupNo);

                String email = getCellValue(row.getCell(15));
                gm.setEmail(email);

                String memName = getCellValue(row.getCell(16));
                gm.setMemName(memName);

                String password = getCellValue(row.getCell(17));
                gm.setPassword(password);

                String memProfession = getCellValue(row.getCell(18));
                gm.setMemProfession(memProfession);

                gmVipMembers.add(gm);
                logger.info("插入數據完成");

            }
        }
        excelDao.batchInsert(gmVipMembers); //批量插入 五秒完成
        long endTime = System.currentTimeMillis();
        long totaltime = endTime - startTime;
        logger.info("[消耗時間爲]{}", totaltime);
        logger.info("[第一條數據爲]{}", JSON.toJSON(gmVipMembers.get(0)));

        return rows;
    }

    public String getCellValue(Cell cell) {
        String value = "";
        if (cell != null) {
            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC:// 數字
                    value = cell.getNumericCellValue() + " ";
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        if (date != null) {
                            value = new SimpleDateFormat("yyyy-MM-dd").format(date); //  日期格式化
                        } else {
                            value = "";
                        }
                    } else {
                        //  解析cell時候 數字類型默認是double類型的 可是想要獲取整數類型 須要格式化
                        value = new DecimalFormat("0").format(cell.getNumericCellValue());
                    }
                    break;
                case HSSFCell.CELL_TYPE_STRING: //  字符串
                    value = cell.getStringCellValue();
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:   //  Boolean類型
                    value = cell.getBooleanCellValue() + "";
                    break;
                case HSSFCell.CELL_TYPE_BLANK:   // 空值
                    value = "";
                    break;
                case HSSFCell.CELL_TYPE_ERROR: // 錯誤類型
                    value = "非法字符";
                    break;
                default:
                    value = "未知類型";
                    break;
            }

        }
        return value.trim();
    }

}
複製代碼
  • 5.mapper.xml

因爲excel表格是多條數據,因此放到集合裏面遍歷賦值java

<?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.gmos.vip.system.dao.ExcelDao">

    <insert id="batchInsert" parameterType="java.util.List">
        insert into gm_vip_member (id, mem_id, real_name,
                                   tel_num, cid, referee_tel_num,
                                   referee_name, integral, birthday,
                                   nation, education, is_marry,
                                   sex, cid_address, detaile_address,
                                   group_no, email, mem_name,
                                   password, mem_profession)
        values
          <foreach collection="list" item="item" index="index" separator=",">
                  (#{item.id,jdbcType=INTEGER}, #{item.memId,jdbcType=VARCHAR}, #{item.realName,jdbcType=VARCHAR},
                #{item.telNum,jdbcType=VARCHAR}, #{item.cid,jdbcType=VARCHAR}, #{item.refereeTelNum,jdbcType=VARCHAR},
                #{item.refereeName,jdbcType=VARCHAR}, #{item.integral,jdbcType=VARCHAR}, #{item.birthday,jdbcType=DATE},
                #{item.nation,jdbcType=VARCHAR}, #{item.education,jdbcType=VARCHAR}, #{item.isMarry,jdbcType=VARCHAR},
                #{item.sex,jdbcType=VARCHAR}, #{item.cidAddress,jdbcType=VARCHAR}, #{item.detaileAddress,jdbcType=VARCHAR},
                #{item.groupNo,jdbcType=VARCHAR}, #{item.email,jdbcType=VARCHAR}, #{item.memName,jdbcType=VARCHAR},
                #{item.password,jdbcType=VARCHAR}, #{item.memProfession,jdbcType=VARCHAR})
          </foreach>
    </insert>

</mapper>
複製代碼
  • 6.前臺index.html頁面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上傳excel表格測試</title>
</head>
<body>

    <form role="form" action="/importExcel" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <label for="exampleInputFile">上傳Excel數據表</label>
            <input type="file" id="exampleInputFile" name="myFile">
            <p class="help-block">請選擇合適的Excel模板文件</p>
        </div>

        <button type="submit" class="btn btn-info">導入</button>
    </form>
<h1>==========================================</h1>

    <form role="form" action="/downloadExcel" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <label>下載Excel模板</label>
        </div>
        <button type="submit" class="btn btn-info">下載</button>
    </form>
<h1>=====從數據庫導出數據到excel=====================================</h1>

<form role="form" action="/downMysqlForExcel" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label>導出數據到excel</label>
    </div>
    <button type="submit" class="btn btn-info">下載</button>
</form>
</body>
</html>
複製代碼
  • 7.controller

跳轉到導入頁面的控制器web

@Controller
@CrossOrigin(value = "*")//容許跨域訪問
public class ExcelPageController {

    @RequestMapping(value = "/importExcelHtml")
    public String excelHtml() {
        return "index";
    }
}
複製代碼

controller:spring

1.導入excel數據到sql

2.下載空的excel模板數據庫

2.從數據庫導出數據到excelapache

package com.gmos.vip.system.controller;

import com.gmos.vip.system.dao.GmVipMemberMapper;
import com.gmos.vip.system.model.GmVipMember;
import com.gmos.vip.system.service.ExcelImportService;
import com.gmos.vip.system.service.GmUserService;
import com.gmos.vip.system.service.GmVipMemberService;
import com.sun.deploy.net.HttpResponse;
import org.apache.poi.hssf.usermodel.*;
import org.json.JSONException;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author BI
 * @date 2019/1/4 - 13:52
 */
@RestController
@CrossOrigin(value = "*")//容許跨域訪問

public class ExcelController {

    private final static org.slf4j.Logger logger = LoggerFactory.getLogger(ExcelController.class);

    @Autowired
    private ExcelImportService excelImportService;

    @Autowired
    private GmVipMemberService gmVipMemberService;

    /*
    Excel導入數據到數據庫
     */
    @PostMapping("/importExcel")
    public Map importExcel(@RequestParam(value = "myFile", required = true) MultipartFile myFile, HttpServletRequest request) throws JSONException {

        if (request instanceof MultipartHttpServletRequest) {
            ModelAndView modelAndView = new ModelAndView();

            Integer nums = excelImportService.importExcel(myFile);
            modelAndView.addObject("msg", "導入數據成功");
        }
        Map map = new HashMap();
        map.put("msg", "導入成功");
        return map;
    }

    /*
    下載一個空的模板
     */
    @PostMapping("/downloadExcel")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
        String fileName = "vipTemplate.xlsx";// 設置文件名,根據業務須要替換成要下載的文件名
        if (fileName != null) {
            //設置文件路徑
            //String realPath = "F://upfile//";
            String realPath = "D://JAVA//ideaWorkSpace//gmos-vip//src//main//resources//templates//ExcelTemplates";
            File file = new File(realPath, fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 設置強制下載不打開
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    logger.info("下載成功");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

    /*
    從數據庫導出數據到excel
    /
    @PostMapping("/downMysqlForExcel")
    public void downloadMysqlForExcel(HttpServletResponse response) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");

        //這裏的查詢接口和mapper須要本身寫,我調的是查詢全部
        List<GmVipMember> gmVipMembers = gmVipMemberService.findAll();
        String fileName = "vipInfo"+".xlsx"; //設置要導出的文件的名字

        //新增單元行,而且設置單元格數據
        int rowNum = 1;

        //headers表示excel表中第一行的表頭
        String[] headers = {"卡號","真實姓名","手機號","身份證號碼","推薦人手機號","推薦人姓名","積分","出生年月","民族","學歷","婚姻情況","性別",
                "身份證地址","詳細住址","羣號","郵箱","會員用戶名","會員密碼","職業"};

        //在excel中添加表頭
        HSSFRow row = sheet.createRow(0);

        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查詢到的數據放入對應的列
        for(GmVipMember gmVip:gmVipMembers){
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(gmVip.getMemId());
            row1.createCell(1).setCellValue(gmVip.getRealName());
            row1.createCell(2).setCellValue(gmVip.getTelNum());
            row1.createCell(3).setCellValue(gmVip.getCid());
            row1.createCell(4).setCellValue(gmVip.getRefereeTelNum());
            row1.createCell(5).setCellValue(gmVip.getRefereeName());
            row1.createCell(6).setCellValue(gmVip.getIntegral());
            row1.createCell(7).setCellValue(gmVip.getBirthday());
            row1.createCell(8).setCellValue(gmVip.getNation());
            row1.createCell(9).setCellValue(gmVip.getEducation());
            row1.createCell(10).setCellValue(gmVip.getIsMarry());
            row1.createCell(11).setCellValue(gmVip.getSex());
            row1.createCell(12).setCellValue(gmVip.getCidAddress());
            row1.createCell(13).setCellValue(gmVip.getDetaileAddress());
            row1.createCell(14).setCellValue(gmVip.getGroupNo());
            row1.createCell(15).setCellValue(gmVip.getEmail());
            row1.createCell(16).setCellValue(gmVip.getMemName());
            row1.createCell(17).setCellValue(gmVip.getPassword());
            row1.createCell(18).setCellValue(gmVip.getMemProfession());
            rowNum++;
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

}

複製代碼
相關文章
相關標籤/搜索