Java实现Excel表格数据批量导入

一、前台上传Excel表格,传递到后台

<input type="file" name="excel" id="excel" accept="application/vnd.ms-excel"/>

其中accept限定上传的文件只能是.xls文件

function uploadFile() {
        var file = document.getElementById("excel").files[0];
        if (file) {
            var formData = new FormData();
            formData.append("excel", file);
            $.ajax({
                url: 'cdc/providentFund/importProvidentFund',
                type: 'POST',
                cache: false,
                data: formData,
                //这个参数是jquery特有的,不进行序列化,因为我们不是json格式的字符串,而是要传文件
                processData: false,
                //注意这里一定要设置contentType:false,不然会默认为传的是字符串,这样文件就传不过去了
                contentType: false,
                success: function (data) {
                    if (data.code==200){
                        swal({
                            title: "导入成功",
                            type: "success"
                        });
                    }else{
                        swal({
                            title: "导入失败",
                            type: "error"
                        });
                    }
                }
            });
        }
        else {
            swal({
                title: "请选择上传文件",
                type: "warning"
            })
        }
    }

二,后台接收并录入数据库

导包,pom文件添加依赖

 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>

Java代码:

   /**
     * Excel表格数据导入
     * @param request
     * @param response
     */
    @PostMapping(value = "importProvidentFund")
    @PreAuthorize("hasAuthority('edit')")
    @ResponseBody
    public JSONObject importExcel(HttpServletRequest request, HttpServletResponse response){
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code",200);
        Part part=null;
        try {
            part=request.getPart("excel");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
        Workbook workbook =null;
        try {
            workbook = new HSSFWorkbook(part.getInputStream());//获取Excel文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        Sheet sheet=workbook.getSheetAt(0);//获取表格,第一个表格
//        获取sheet中最后一行行号
        int lastRowNum = sheet.getLastRowNum();//获取表格有多少行数据
        for (int i = 1; i <= lastRowNum; i++) {
            //代码解释:获取当前行中的内容
            Row row = sheet.getRow(i); //获取行
            int cell = row.getLastCellNum(); //获取有多少列
            if(row !=null && cell!=0){
                ProvidentFund providentFund=new ProvidentFund(); //将每一项的值添加到对象中
                providentFund.setEmployeeAccountNumber(row.getCell(0).getStringCellValue());
                providentFund.setPersonName(row.getCell(1).getStringCellValue());
                //会损失精度,转成字符串在生成BigDecimal对象
                providentFund.setBeforeMonthPay(getValue(row.getCell(2)));
                providentFund.setDepositBase(getValue(row.getCell(3)));
                providentFund.setAfterMonthPay(getValue(row.getCell(4)));
                providentFund.setAdjustMoney(getValue(row.getCell(5)));
                Date date =new Date();
                providentFund.setCreateTime(date);
                providentFund.setUpdateTime(date);
                boolean b = providentFundService.insert(providentFund);//保存到数据库中
                if (!b){
                    jsonObject.put("code",500);
                }
            }
        }
        return jsonObject;
    }

其中getValue方法是将double类型的值转换为BigDecimal对象

 private BigDecimal getValue(Cell cell){
        return BigDecimal.valueOf(cell.getNumericCellValue());
    }

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值