excel文件导入导出

一、execl文件导入

1、前端(angular4,多余内容省略)

html文件

<!--导入文件-->
<nz-modal [(nzVisible)]="detailModal1.show" [nzTitle]="detailModal1.title" [nzFooter]="updateModelFooter1"
          (nzOnCancel)="handleDetailCancel1()" nzWidth="450px">
  <input type="file" (change)="importExcel($event)" multiple="false" accept=".xls,.xlsx,.txt">
</nz-modal>

ts文件

this.file = new FormData();
/**
   * 选择导入文件
   * @param
   */
  importExcel(event: any): void {
    this.file.append('file', event.target.files[0]);
  }
/**
   * 导入
   */
  importExcel1() {
    const params = this.file;
    this.service.importTerminal(params).subscribe((resData: TerminalManageServiceNs.UfastHttpAnyResModel) => {
      if (resData.code == 0) {
        this.detailModal1.show = false;
        this.showMessageService.showToastMessage('操作成功', 'success');
      } else {
        this.showMessageService.showAlertMessage('', resData.message + ':' + resData.value , 'warning');
      }
    }, (error: any) => {
      this.tableConfig.loading = false;
      this.showMessageService.showAlertMessage('', error.message, 'error');
    });
  }

2、后端

 工具类

 /**
     * @param entityClass excel中每一行数据的实体类
     * @param in          excel文件
     * @param fields      字段名字
     *                    需要注意的是这个方法中的map中:
     *                    excel表格中每一列名为键,每一列对应的实体类的英文名为值
     * @throws Exception
     * @author Lyy
     */
    public static <T> List<T> ExecltoListXLSX(InputStream in, Class<T> entityClass,
                                              Map<String, String> fields) throws Exception {

        List<T> resultList = new ArrayList<T>();

//        XSSFWorkbook workbook = new XSSFWorkbook(in);
        Workbook workbook = WorkbookFactory.create(in);
//        Sheet hssfSheet = workbook.getSheetAt(0);  //示意访问sheet

        // excel中字段的中英文名字数组
        String[] egtitles = new String[fields.size()];
        String[] cntitles = new String[fields.size()];
        Iterator<String> it = fields.keySet().iterator();
        int count = 0;
        while (it.hasNext()) {
            String cntitle = (String) it.next();
            String egtitle = fields.get(cntitle);
            egtitles[count] = egtitle;
            cntitles[count] = cntitle;
            count++;
        }

        // 得到excel中sheet总数
        int sheetcount = workbook.getNumberOfSheets();

        if (sheetcount == 0) {
            workbook.close();
            throw new Exception("Excel文件中没有任何数据");
        }

        // 数据的导出
        for (int i = 0; i < sheetcount; i++) {
//            XSSFSheet sheet = workbook.getSheetAt(i);
            Sheet sheet = workbook.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            // 每页中的第二行为标题行,对标题行的特殊处理
            Row firstRow = sheet.getRow(0);
            int celllength = firstRow.getLastCellNum();

            String[] excelFieldNames = new String[celllength];
            LinkedHashMap<String, Integer> colMap = new LinkedHashMap<String, Integer>();

            // 获取Excel中的列名
            for (int f = 0; f < celllength; f++) {
                Cell cell = firstRow.getCell(f);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                excelFieldNames[f] = cell.getStringCellValue().trim();
                // 将列名和列号放入Map中,这样通过列名就可以拿到列号
                for (int g = 0; g < excelFieldNames.length; g++) {
                    colMap.put(excelFieldNames[g], g);
                }
            }
            // 由于数组是根据长度创建的,所以值是空值,这里对列名map做了去空键的处理
            colMap.remove(null);
            // 判断需要的字段在Excel中是否都存在
            // 需要注意的是这个方法中的map中:中文名为键,英文名为值
            boolean isExist = true;
            List<String> excelFieldList = Arrays.asList(excelFieldNames);
            for (String cnName : fields.keySet()) {
                if (!excelFieldList.contains(cnName)) {
                    isExist = false;
                    break;
                }
            }
            // 如果有列名不存在,则抛出异常,提示错误
            if (!isExist) {
                workbook.close();
                throw new Exception("Excel中缺少必要的字段,或字段名称有误");
            }
            // 将sheet转换为list
            for (int j = 1; j <= sheet.getLastRowNum(); j++) {
                Row row = sheet.getRow(j);
                // 根据泛型创建实体类
                T entity = entityClass.newInstance();
                // 给对象中的字段赋值
                for (Map.Entry<String, String> entry : fields.entrySet()) {
                    // 获取中文字段名
                    String cnNormalName = entry.getKey();
                    // 获取英文字段名
                    String enNormalName = entry.getValue();
                    // 根据中文字段名获取列号
                    int col = colMap.get(cnNormalName);
                    // 获取当前单元格中的内容
                    String content = null;
                    if ("trade_time".equals(enNormalName)) {
                        Cell cell = row.getCell(col);
                        Date dateCellValue = cell.getDateCellValue();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        content = simpleDateFormat.format(dateCellValue);
                    } else if ("vice_no".equals(enNormalName)) {
                        Cell cell = row.getCell(col);
                        cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                        content = cell.getStringCellValue();
                    } else if ("trade_num".equals(enNormalName)) {
                        Cell cell = row.getCell(col);
                        cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                        content = cell.getStringCellValue();
                    } else {
                        row.getCell(col).setCellType(Cell.CELL_TYPE_STRING);
                        content = row.getCell(col).toString().trim();
                    }
                    // 给对象赋值
                    setValueByName(enNormalName, content, entity);
                }
                resultList.add(entity);
            }
        }
        workbook.close();
        return resultList;
    }


    private static void setValueByName(String fieldName,
                                       Object fieldValue, Object o) throws Exception {

        Field field = getFieldByName(fieldName, o.getClass());
        if (field != null) {
            field.setAccessible(true);

            // 根据字段类型给字段赋值
            if ("terminalNumber".equals(fieldName)) {
                field.set(o, String.valueOf(fieldValue));
            } else if ("simCard".equals(fieldName)) {
                field.set(o, String.valueOf(fieldValue));
            } else if ("supplier".equals(fieldName)) {
                field.set(o, String.valueOf(fieldValue));
            } else if ("".equals(fieldName)) {
                field.set(o, String.valueOf(fieldValue));
            } else if ("workPersonnelName".equals(fieldName)) {
                field.set(o, String.valueOf(fieldValue));
            } else if ("trade_time".equals(fieldName)) {
                field.set(o, String.valueOf(fieldValue));
            } else if ("oil_name".equals(fieldName)) {
                field.set(o, String.valueOf(fieldValue));
            } else if ("trade_num".equals(fieldName)) {
                field.set(o, Double.valueOf(String.valueOf(fieldValue)));
            }
        } else {
            throw new Exception(o.getClass().getSimpleName() + "类不存在字段名 "
                    + fieldName);
        }
    }

service层和controller层就不写了,直接在service层根据业务需求调用工具类

猜你喜欢

转载自www.cnblogs.com/kcbrs/p/13354006.html