簡單導入Excel

簡單導入Excel

1.頁面上傳文件
這裏用的vue的插件

 <el-upload
        class="upload-demo"
        action="http://localhost:8089/file/exportExcel.do"
        multiple
        :limit="3">
        <el-button size="small" type="primary">導入Excel</el-button>
      </el-upload>

controller

 @RequestMapping("exportExcel")
    public void exportExcel(MultipartFile file){

        productService.exportExcel(file);

    }

service層【所有的業務邏輯都在這裏】

  public void exportExcel(MultipartFile file) {

        //通過WorkbookFactory加載文件
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(file.getInputStream());
            //獲取sheet
            Sheet sheet = workbook.getSheetAt(0);

            //獲取當前sheet一共有多少行
            int lastRowNum = sheet.getLastRowNum();

            Row row;

            //查詢出所有的brand集合,爲了判斷brandName對應的id
            List<Brand> brandList = brandService.queryListAll();

            //爲了避免多次與數據庫交互,定義一個list集合進行批量增加
            List productList = new ArrayList();

            for (int i = 1; i <= lastRowNum; i++) {

                Product product = new Product();

                //從第一行開始讀取
                row = sheet.getRow(i);

                //讀取第0列開始,productName
                Cell cell = row.getCell(0);

                //獲取當前列的信息
                String productName = cell.getStringCellValue();
                //得出的值放到product中,新增
                product.setProductName(productName);

                //讀取第1列
                cell= row.getCell(1);
                //獲取當前列的信息,是數字類型的,不能用String
                String brandName = cell.getStringCellValue();

                Integer brandId = null;
                //進行遍歷查詢brandName與那個相等,拿到id
                for (Brand brand : brandList) {
                    if(brandName.equals(brand.getBrandName())){
                        brandId = brand.getId();
                    }
                }
                Brand brand = new Brand();
                brand.setBrandName(brandName);
              //  brand.setCreateDate(new Date());
                //如果品牌名稱沒有查出來,則進行增加(id需要在增加以後返回)
                if(brandId == null){
                    brandService.insertBrand(brand);
                    brandId= brand.getId();
                }
                product.setBrandId(brandId);


                //讀取第2列
                cell= row.getCell(2);
                double productPrice = cell.getNumericCellValue();
                product.getProductPrice(productPrice);

                product.setCreateDate(new Date());

                productList.add(product);

            }
            productMapper.insertBath(productList);


        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }

就可以了

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