zoukankan      html  css  js  c++  java
  • 使用 xls 文件 导入

    https://www.cnblogs.com/rensheng/p/10434877.html

    前端  页面的代码:

    点击按钮 触发的弹框导入事件。 也可以用使用form表单

      <div style="float:right; display: inline-block;">
           <button type="button" id="importBut" class="btn btn-primary">导入</button>
       </div>

    对应的js代码: 这是使用了 zeroModal 插件的弹框。 在使用form 表单 利用了ajax 提交

      $("#importBut").click(function () {
            importBut();
        });
    
    
    // 导入弹框
    function importBut() {
            zeroModal.closeAll();
            zeroModal.show({
                title: '导入',
                content:'<form enctype="multipart/form-data" method="post" id="importForm">' +
                    '<div class="form-group">' +
                    '   <div class="form-cont">' +
                    '        <input type="file" class="form-control"  name="file" />' +
                    '   </div>' +
                    '</div>' +
                    ' <div class="form-group">' +
                    '     <button type="button" style="float: right;margin-right: 70px;" id="saveBtn" class="btn btn-primary">保存</button>' +
                    ' </div>'+
                    '</form>',
                 '470px',
                height: '260px',
                onLoad: function () {
                    $('.zeromodal-container').css("top", "80px");
                },
                onComplete: function () {
                    $('#saveBtn').unbind("click").click(function () {
                        var action = contextPath + "/manmachine/fileExcelImportCommonData";
                        // $("#importForm").attr("action",action);
                        // $("#importForm").formAction(action);
                        // $("#importForm").submit();
                        var formData = new FormData($("#importForm")[0]);
                // 这里还可以加入别的参数 在后台接收的时候 可以用
    @RequestParam(value = "selectCorpusId", required = false)String selectCorpusId

                formaData.append("id",id);
    $.ajax({ url: action, type:
    "POST", data: formData, async: false, cache: false, contentType: false, processData: false, success: function (data) { alert("成功!"); }, error: function (returndata) { console.log("====================Error=========================="); } }); }); } }); }

    后台接收代码:

      /**
         * 导入
         * @param file
         * @return
         */
        @RequestMapping(value="/fileExcelImportCommonData",method= RequestMethod.POST)
        @ResponseBody
        public Output fileExcelImport(MultipartFile file) {
            Output output = new Output();
            try {
                commonDataService.fileExcelImport(file);
                output.setData(true);
            } catch (Exception e) {
                logger.error("",e);
                output.setData(false);
            }
            return output;
        }

    对应的serviceimpl 逻辑层的实现:

     private final static String XLS = "xls";
        private final static String XLSX = "xlsx";
    
        @Override
        public Integer fileExcelImport(MultipartFile myFile) throws Exception {
            //获得文件名
            Workbook workbook = null ;
            String fileName = myFile.getOriginalFilename();
            if(fileName.endsWith(XLS)){
                //2003
                workbook = new HSSFWorkbook(myFile.getInputStream());
            }else if(fileName.endsWith(XLSX)){
                //2007
                workbook = new XSSFWorkbook(myFile.getInputStream());
            }else{
                throw new Exception("文件不是Excel文件");
            }
    
            Sheet sheet = workbook.getSheet("Sheet1");
            int rows = sheet.getLastRowNum();// 指的行数,一共有多少行+
            // 获取所有列
    
            if(rows==0){
                throw new Exception("请填写数据");
            }
    
            // 取xls 中 表头的字段的坐标
            Map<String,Integer>  mapIndex = getSheetTitleIndex(sheet);
    
            // 循环所有的行  从第二行开始  数据开始
            for (int i = 0; i < rows; i++) {
                // 读取所有的行从第二行开始读取
                Row row = sheet.getRow(i+1);
                // 行不为空
                if (row != null) {
                    // **读取cell**
                    CommonData commonData = new CommonData();
                    String title = getCellValue(row.getCell(mapIndex.get("标题")));
                    String label = getCellValue(row.getCell(mapIndex.get("作者")));
                    String value = getCellValue(row.getCell(mapIndex.get("来源")));
    
                    commonData.setId(IdCreator.getUUID());
                    commonData.setName(name);
                    commonData.setValue(value);
                    commonData.setLabel_(label);
    
                    // 存入list 中
    //                commonDataDao.save(commonData);
    //
    //                if( (i % 2000) == 0 ){
    //                    Thread.sleep(2*1000);
    //                }
                }
            }
            return rows-1;
        }
    
    /**
         * 取xls 表格中第一行表格的坐标
         * @param
         */
        private Map<String,Integer> getSheetTitleIndex(Sheet sheet) {
            Map<String,Integer> map = new HashMap<>();
            // 获取表格中第一行的标题的下标
             Row rows = sheet.getRow(0);
                for(Cell cell:rows){
                    cell.setCellType(cell.CELL_TYPE_STRING);//不推荐使用的方法,但是取出列有数字的话,要转换一下
                    if(!StringUtils.isBlank(cell.getStringCellValue())){
                        if(cell.getStringCellValue().equals("标题")){
                                map.put("标题",cell.getColumnIndex());
                        }
                        if(cell.getStringCellValue().equals("作者")){
                            map.put("作者",cell.getColumnIndex());
                        }
                        if(cell.getStringCellValue().equals("来源")){
                            map.put("来源",cell.getColumnIndex());
                        }
                    }
                }
    
                return map;
        }
    /**
    * 获得Cell内容
    *
    * @param cell
    * @return
    */
    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 {
    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_FORMULA: // 公式
    value = cell.getCellFormula() + "";
    break;
    case HSSFCell.CELL_TYPE_BLANK: // 空值
    value = "";
    break;
    case HSSFCell.CELL_TYPE_ERROR: // 故障
    value = "非法字符";
    break;
    default:
    value = "未知类型";
    break;
    }
    }
    return value.trim();
    }
     
  • 相关阅读:
    SSM框架--详细整合教程
    ssh--整合注意事项
    SSH--三大框架整合原理
    springMVC的流程
    java框架问题整理
    集合的体系
    java异常机制
    java知识点
    Java编程思想【Thinking in java】
    实验三 指令实验(一)
  • 原文地址:https://www.cnblogs.com/yishuo/p/12972481.html
Copyright © 2011-2022 走看看