poi导入excel文件

本文介绍了一个使用Apache POI库将Excel文件导入数据库的Java应用实例。前端通过Bootstrap模态框选择文件,后端使用MultipartFile处理上传,并在服务层解析Excel数据,最终批量插入数据库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近公司要求做一个导入excel文件到数据库的功能,就参照网上的博客做了一个小例子.

首先准备poi-3.17.jar,poi-ooxml-3.17.jar,poi-ooxml-schemas-3.17.jar

前端代码modal.jsp:

我是用的bootstrap插件(modal对话框)

<div class="modal" id="import">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title">导入</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" id="import">
        <div class="form-group">
<label class="col-sm-2 control-label">文件:</label>
<div class="col-sm-5">
<input type="file" name="uploadFile" id="file"/>
</div>
<div class="col-sm-3">
<button type="button" class="btn btn-primary" id="importBtn" >导入</button>
</div>
</div>
<div class="form-group text-center tips">
<p class="message error"></p>
</div>
</form>
</div>
</div>
</div>

</div>

js文件

$("#importBtn").off('click').on('click', function (e) {
 
 var fd = new FormData();
 fd.append('uploadFile', $('#file')[0].files[0]);
 
 var fileExtend=$('#file').val().substring($('#file').val().lastIndexOf('.')).toLowerCase();
 if(fileExtend !=".xls"){
$("#import").find(".tips").html('<p class="error" style="color:red;">仅支持(.xls)类型的文件</p>');
 return ;
 }


 $.ajax({
             type: 'post',
             url: 'thresholdManage/import',
             data: fd,
             dataType:'json',
             processData: false,
             contentType: false,
             success: function (data) {
            if(data.success){       
              $("#import").find(".tips").html('<p class="error" style="color:red;">导入成功!!</p>');
              }else{
              $("#import").find(".tips").html('<p class="error" style="color:red;">导入失败!!</p>');
              }
                 
             },
             error: function (xhr) {
                 console.log(xhr);
             }
    });

});

后台代码:

controller直接调用接口比较简单省略

接口service

public List<TDimThreshold> importFile(MultipartFile mFile, String rootPath) {
// TODO Auto-generated method stub
List<TDimThreshold> thresholdList = new ArrayList<TDimThreshold>();
        
        String fileName = mFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        String ym = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String filePath = "files/" + ym + fileName;
        try {
            File file = new File(rootPath + filePath);
            if (file.exists()) {
                file.delete();
                file.mkdirs();
            }else {
                file.mkdirs();
            }
            mFile.transferTo(file);
            
            if ("xls".equals(suffix) || "XLS".equals(suffix)) {
            thresholdList = importXls(file);
            m_thresholdDao.importFile(thresholdList);
            }else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
        
        return thresholdList;
}


private List<TDimThreshold> importXls(File file) {

        List<TDimThreshold> thresholdList = new ArrayList<TDimThreshold>();

InputStream is = null;
HSSFWorkbook hWorkbook = null;
try {
            is = new FileInputStream(file);
            hWorkbook = new HSSFWorkbook(is);
            HSSFSheet hSheet = hWorkbook.getSheetAt(0);
            if (null != hSheet){  
                for (int i = 1; i < hSheet.getPhysicalNumberOfRows(); i++){  
                TDimThreshold threshold = new TDimThreshold();
                    HSSFRow hRow = hSheet.getRow(i);
                    
                    threshold.setFACTOR_ITEM_ID(new Double(hRow.getCell(0).toString()).shortValue());
                    threshold.setHIGHT_LEVEL1(Float.parseFloat(hRow.getCell(1).toString()));
                    threshold.setHIGHT_LEVEL2(Float.parseFloat(hRow.getCell(2).toString()));
                    threshold.setHIGHT_LEVEL3(Float.parseFloat(hRow.getCell(3).toString()));
                    threshold.setLOW_LEVEL1(Float.parseFloat(hRow.getCell(4).toString()));
                    threshold.setLOW_LEVEL2(Float.parseFloat(hRow.getCell(5).toString()));
                    threshold.setLOW_LEVEL3(Float.parseFloat(hRow.getCell(6).toString()));
                    threshold.setSCHEME_ID(new Double(hRow.getCell(7).toString()).shortValue());
                    threshold.setSENSOR_ID((int)Float.parseFloat(hRow.getCell(8).toString()));
                    thresholdList.add(threshold);
                }  
            }  
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (null != is) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            
            if (null != hWorkbook) {
                try {
                    hWorkbook.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }    
        

        return thresholdList;

    }

dao层就是批量添加数据,比较简单就不写了



这样我们就完成了一个简单的导入excel文件的例子了

转载博客:http://www.cnblogs.com/littlecharacter/p/5580676.html

如有不足请指正!








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值