SpringBoot 簡潔明瞭將導入Excel到數據庫

以下有兩種構建工程看看你選擇哪個

maven依賴

<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>3.17</version>
</dependency>
		
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>3.17</version>
</dependency>

Gradle依賴

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

控制層代碼

    @ApiOperation(value = "導入", notes = "導入", produces = "text/plain")
    @PostMapping("/v2/payable/importOrder")
    @PreAuthorize("hasRole('importOrder-payable-v2')")
    public JSONResult importOrder(MultipartFile file) throws Exception {
        orderService.importOrder(Long.parseLong(SecurityContextHolder.getSubject().getId()),file);
        return JSONResult.ok();
    }

 

服務層代碼

    /**
     * 導入
     * @param file 文件
     */
    void importOrder(Long userId,MultipartFile file) throws Exception;

實現層代碼(這裏是我多表添加操作數據)

@Override
    @Transactional
    public void importOrder(Long userId, MultipartFile file) throws Exception {
        //調用封裝好的工具
        ExcelImportUtil importUtil = new ExcelImportUtil(file);
        //調用導入的方法,獲取sheet表的內容
        List<Map<String, String>> maps = importUtil.readExcelContent();
        //獲取自定義表頭標題數據
        Map<String, Object> someTitle = importUtil.readExcelSomeTitle();
        //導入訂單表
        PayableOrder payableOrder = PayableOrder.builder()
                .entryTime(someTitle.get("date").toString())
                .remark(someTitle.get("remark").toString())
                .createTime(DateTimeUtils.dateTimeToString(LocalDateTime.now()))
                .createBy(String.valueOf(userId))
                .status(1)
                .type(1)
                .build();
        //執行添加到數據庫
        payableOrderDao.save(payableOrder);
         //獲取訂單號
        Long id = payableOrder.getId();
        //導入訂單詳情表
        List<PayableOrderDetail> orderDetails = maps.stream().filter(Objects::nonNull).map(map -> {
            Customer customer = customerDao.findByEnCode(map.get("供應商編碼"));
            if (Objects.isNull(customer)) throw new HandleException("供應商不存在");
            return PayableOrderDetail.builder()
                    .qPayableId(id)
                    .supplierCode(map.get("供應商編碼"))
                    .cCustomerId(customer.getId())
                    .supplierName(map.get("供應商名稱"))
                    .registerAddr(map.get("註冊地址"))
                    .bankAccount(map.get("銀行賬號"))
                    .openBank(map.get("開戶行"))
                    .telephone(map.get("聯繫方式"))
                    .contact(map.get("主聯繫人"))
                    .remark(map.get("備註"))
                    .payAmount(BigDecimal.valueOf(Double.parseDouble(map.get("期初應付金額"))))
                    .createTime(DateTimeUtils.dateTimeToString(LocalDateTime.now()))
                    .createBy(String.valueOf(userId))
                    .status(1).build();
        }).collect(Collectors.toList());
         //批量添加到訂單詳情
        orderDetailDao.saveAll(orderDetails);
    }

導入工具類

package com.softwarebr.ashe.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ZHY
 * @date 2020/6/17 15:56
 */
public class ExcelImportUtil {
    private Workbook wb;
    private Sheet sheet;
    private Row row;

    /**
     * 讀取Excel
     *
     * @author ZHY
     */
    public ExcelImportUtil(MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        String ext = filename.substring(filename.lastIndexOf("."));
        InputStream is = file.getInputStream();
        if (".xls".equals(ext)) {
            wb = new HSSFWorkbook(is);
        } else if (".xlsx".equals(ext)) {
            wb = new XSSFWorkbook(is);
        } else {
            wb = null;
        }
    }

    /**
     * 讀取Excel表格表頭的內容輸出
     *
     */
    public List<Map<String, Object>> readExcelTitleOut() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if (wb != null) {
            sheet = wb.getSheetAt(0);
            row = sheet.getRow(0);
            // 標題總列數
            int colNum = row.getPhysicalNumberOfCells();

            System.out.println("colNum:" + colNum);

            Map<String, Object> map = new LinkedHashMap<String, Object>();

            for (int i = 0; i < colNum; i++) {
                String stringCellValue = row.getCell(i).getStringCellValue();
                map.put(stringCellValue, null);
            }
            list.add(map);
            return list;
        }
        return list;
    }

    /**
     * 讀取Excel表格表頭
     *
     */
    public String[] readExcelTitle() {
        String[] title = {};
        if (wb != null) {
            sheet = wb.getSheetAt(0);
            row = sheet.getRow(4);
            // 標題總列數
            int colNum = row.getPhysicalNumberOfCells();

            System.out.println("colNum:" + colNum);

            title = new String[colNum];

            for (int i = 0; i < colNum; i++) {
                title[i] = row.getCell(i).getStringCellValue().replaceAll("\\s+", "");
            }
        }
        return title;
    }

    /**
     * 讀取Excel表格的某一個數值
     * @return
     */
    public  Map<String, Object> readExcelSomeTitle(){
        Map<String, Object> map = new LinkedHashMap<>();
        if (wb != null) {
            sheet = wb.getSheetAt(0);
            String title = parseExcel(sheet.getRow(2).getCell(1));
            String remark = parseExcel(sheet.getRow(3).getCell(1));
            map.put("date",title);
            map.put("remark",remark);
        }
        return map;
    }

    /**
     * 讀取Excel數據內容
     *
     */
    public List<Map<String, String>> readExcelContent() {
        List<Map<String, String>> list = new ArrayList<>();
        if (wb != null) {
            //獲取sheet表
            sheet = wb.getSheetAt(0);
            // 得到總行數
            int rowNum = sheet.getLastRowNum();
            //獲取表頭的標題
            String[] readExcelTitle = readExcelTitle();
            // 正文內容應該從第二行開始,第一行爲表頭的標題
            for (int i = 5; i <= rowNum; i++) {
                row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                Map<String, String> map = new LinkedHashMap<>();
                for (int j = 0; j < readExcelTitle.length; j++) {
                    //獲取每一列的數據值
                    String str = parseExcel(row.getCell(j));
                    //判斷對應行的列值是否爲空
                    if (StringUtils.isNotBlank(str)) {
                        //表頭的標題爲鍵值,列值爲值
                        map.put(readExcelTitle[j], str);
                    }
                }
                //判段添加的對象是否爲空
                if (!map.isEmpty()){
                    list.add(map);
                }
            }
        }
        return list;
    }

    /**
     *
     * 根據Cell類型設置數據
     *
     */
    private String parseExcel(Cell cell) {
        String result = "";
        if (cell != null) {
            SimpleDateFormat sdf = null;
            switch (cell.getCellTypeEnum()) {
                case NUMERIC:// 數字類型
                    if (DateUtil.isCellDateFormatted(cell)) {// 處理日期格式、時間格式
                        if (cell.getCellStyle().getDataFormat() == 20) {
                            sdf = new SimpleDateFormat("HH:mm");
                        } else {// 日期
                            sdf = new SimpleDateFormat("yyyy-MM-dd");
                        }
                        String dateFormat = sdf.format(cell.getDateCellValue());
                        result = dateFormat;
                    } else if (cell.getCellStyle().getDataFormat() == 58) {
                        // 處理自定義日期格式:m月d日(通過判斷單元格的格式id解決,id的值是58)
                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                        double value = cell.getNumericCellValue();
                        Date date = DateUtil.getJavaDate(value);
                        result = sdf.format(date);
                    } else {
                        double value = cell.getNumericCellValue();
                        DecimalFormat format = new DecimalFormat("#.###########");
                        String strVal = format.format(value);
                        result = strVal;
                    }
                    break;
                case STRING:// String類型
                    result = cell.getRichStringCellValue().toString();
                    break;
                default:
                    break;
            }
        }
        return result;
    }
}

 

操作的excel文件,如圖:

 

以上就是操作導入excel文件數據到數據庫,我操作的是MySQL數據庫,其他的數據沒有試過,你們可以試試。

不懂的可以問我,聯繫方式:[email protected]

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章