导入的excel数据封装成实体类

实体类
@ApiModel(value = “ArchivesTransferEntity”)
public class ArchivesTransferEntity implements Serializable {
private static final long serialVersionUID = 1L;
//主键id
@ApiModelProperty(“主键id”)
@ApiParam(value = “主键id”,required = true)
private Integer id;
//行名
@ApiParam(value = “行名”,required = false)
@ApiModelProperty(“行名”)
@MapperCell(cellName = “行名”)
private String bankName;
//项目号
@ApiParam(value = “项目号”,required = false)
@ApiModelProperty(value = “项目号”)
@MapperCell(cellName = “项目号”)
private String projectNum;
//年度序号
@ApiParam(value = “年度序号”,required = false)
@ApiModelProperty(value = “年度序号”)
@MapperCell(cellName = “年度序号”)
private String yearNum;
//档案编号
@ApiParam(value = “档案编号”,required = false)
@ApiModelProperty(“档案编号”)
@MapperCell(cellName = “档案编号”)
private String fileNum;
//产品码
@ApiParam(value = “产品码”,required = false)
@ApiModelProperty(“产品码”)
@MapperCell(cellName = “产品码”)
private String productCode;
//借款人
@ApiParam(value = “借款人”,required = false)
@ApiModelProperty(“借款人”)
@MapperCell(cellName = “借款人”)
private String customerName;
//贷款金额
@ApiParam(value = “贷款金额”,required = false)
@ApiModelProperty(“贷款金额”)
@MapperCell(cellName = “贷款金额”)
private String approvedAmount;
//贷款期数
@ApiParam(value = “贷款期数”,required = false)
@ApiModelProperty(“贷款期数”)
@MapperCell(cellName = “贷款期数”)
private String termOfLoan;
//贷款起止日
@ApiParam(value = “贷款起止日”,required = false)
@ApiModelProperty(“贷款起止日”)
@MapperCell(cellName = “贷款起止日期”)
private String loanDate;
//贷款账号
@ApiParam(value = “贷款账号”,required = false)
@ApiModelProperty(“贷款账号”)
@MapperCell(cellName = “贷款帐号”)
private String loanAccount;
//流水号
@ApiParam(value = “流水号”,required = false)
@ApiModelProperty(“流水号”)
@MapperCell(cellName = “流水号”)
private String serialNum;
//一级押品编号
@ApiParam(value = “一级押品编号”,required = false)
@ApiModelProperty(“一级押品编号”)
@MapperCell(cellName = “一级押品编号”)
private String primaryCollateralNum;
//二级入库时间
@ApiParam(value = “二级入库时间”,required = false)
@ApiModelProperty(“二级入库时间”)
@MapperCell(cellName = “二级入库时间”)
private String secondaryStorageDate;
//放款日期
@ApiParam(value = “放款日期”,required = false)
@ApiModelProperty(“放款日期”)
private String firstReleaseDate;
//到期日期
@ApiParam(value = “到期日期”,required = false)
@ApiModelProperty(“到期日期”)
private String maturityDate;
//删除状态,0未删除,1已删除
@ApiParam(value = “删除状态,0未删除,1已删除”,required = false)
@ApiModelProperty(“删除状态,0未删除,1已删除”)
private Integer deleteStatus;
//数据上传唯一识别号
@ApiParam(value = “数据上传唯一识别号”,required = false)
@ApiModelProperty(“数据上传唯一识别号”)
private String statusFlag;
//导入时间
@ApiParam(value = “导入时间”,required = false)
@ApiModelProperty(“导入时间”)
private String importDate;

//已读状态,0未读,1已读
@ApiParam(value = "已读状态,0未读,1已读",required = false)
@ApiModelProperty("已读状态,0未读,1已读")
private Integer readStatus;
//校验状态 ,0未校验,1已校验(当校验状态为1,已读状态为0时显示***)
@ApiParam(value = "校验状态 ,0未校验,1已校验",required = false)
@ApiModelProperty("校验状态 ,0未校验,1已校验")
private Integer checkStatus;
//生成状态,0未生成,1已生成
@ApiParam(value = "生成状态,0未生成,1已生成",required = false)
@ApiModelProperty("生成状态,0未生成,1已生成")
private Integer confirmStatus;

/**

  • 用于映射实体类和Excel某列名称

  • @author peiyu
    */
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface MapperCell {

    /**

    • 在excel文件中某列数据的名称
    • @return 名称
      */
      String cellName() default “”;

    /**

    • 在excel中列的顺序,从小到大排
    • @return 顺序
      */
      int order() default 0;
      }
      工具类
      package com.ixilink.common.utils;

import com.ixilink.common.annotation.MapperCell;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.
;

/**

  • 快速简单操作Excel的工具

  • @author peiyu
    */
    public final class FastExcel implements Closeable {

    private static final Logger LOG = LoggerFactory.getLogger(FastExcel.class);
    /**

    • 时日类型的数据默认格式化方式
      */
      private DateFormat format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
      private int startRow;
      private String sheetName;
      private final String excelFilePath;
      private final Workbook workbook;

    /**

    • 构造方法,传入需要操作的excel文件路径
    • @param excelFilePath 需要操作的excel文件的路径
    • @throws IOException IO流异常
    • @throws InvalidFormatException 非法的格式异常
      */
      public FastExcel(String excelFilePath) throws IOException, InvalidFormatException {
      this.startRow = 0;
      this.sheetName = “Sheet1”;
      this.excelFilePath = excelFilePath;
      this.workbook = createWorkbook();
      }

    /**

    • 通过数据流操作excel,仅用于读取数据
    • @param inputStream excel数据流
    • @throws IOException IO流异常
    • @throws InvalidFormatException 非法的格式异常
      */
      public FastExcel(InputStream inputStream) throws IOException, InvalidFormatException {
      this.startRow = 0;
      this.sheetName = “Sheet1”;
      this.excelFilePath = “”;
      this.workbook = WorkbookFactory.create(inputStream);
      }

    /**

    • 通过数据流操作excel
    • @param inputStream excel数据流
    • @param outFilePath 输出的excel文件路径
    • @throws IOException IO流异常
    • @throws InvalidFormatException 非法的格式异常
      */
      public FastExcel(InputStream inputStream, String outFilePath) throws IOException, InvalidFormatException {
      this.startRow = 0;
      this.sheetName = “Sheet1”;
      this.excelFilePath = outFilePath;
      this.workbook = WorkbookFactory.create(inputStream);
      }

    /**

    • 开始读取的行数,这里指的是标题内容行的行数,不是数据开始的那行
    • @param startRow 开始行数
      */
      public void setStartRow(int startRow) {
      if (startRow < 1) {
      throw new RuntimeException(“最小为1”);
      }
      this.startRow = --startRow;
      }

    /**

    • 设置需要读取的sheet名字,不设置默认的名字是Sheet1,也就是excel默认给的名字,所以如果文件没有自已修改,这个方法也就不用调了
    • @param sheetName 需要读取的Sheet名字
      */
      public void setSheetName(String sheetName) {
      // Sheet sheet = this.workbook.getSheet(sheetName);
      // if (null == sheet) {
      // throw new RuntimeException(“sheetName:” + sheetName + " is not exist");
      // }
      this.sheetName = sheetName;
      }

    /**

    • 设置时间数据格式
    • @param format 格式
      */
      public void setFormat(String format) {
      this.format = new SimpleDateFormat(format);
      }

    /**

    • 解析读取excel文件

    • @param clazz 对应的映射类型

    • @param 泛型

    • @return 读取结果
      */
      public List parse(Class clazz) {
      List resultList = null;
      try {
      Sheet sheet = workbook.getSheet(this.sheetName);
      if (null != sheet) {
      resultList = new ArrayList(sheet.getLastRowNum() - 1);
      Row row = sheet.getRow(this.startRow);

           Map<String, Field> fieldMap = new HashMap<String, Field>();
           Map<String, String> titleMap = new HashMap<String, String>();
      
           Field[] fields = clazz.getDeclaredFields();
           //这里开始处理映射类型里的注解
           for (Field field : fields) {
               if (field.isAnnotationPresent(MapperCell.class)) {
                   MapperCell mapperCell = field.getAnnotation(MapperCell.class);
                   fieldMap.put(mapperCell.cellName(), field);
               }
           }
      
           for (Cell title : row) {
               CellReference cellRef = new CellReference(title);
               titleMap.put(cellRef.getCellRefParts()[2], title.getRichStringCellValue().getString().trim());
           }
           int lastRowNum = sheet.getPhysicalNumberOfRows();
           for (int i = this.startRow + 1; i < lastRowNum; i++) {
               T t = clazz.newInstance();
               Row dataRow = sheet.getRow(i);
               for (Cell data : dataRow) {
                   CellReference cellRef = new CellReference(data);
                   String cellTag = cellRef.getCellRefParts()[2];
                   String name = titleMap.get(cellTag);
                   Field field = fieldMap.get(name);
                   if (null != field) {
                       field.setAccessible(true);
                       getCellValue(data, t, field);
                   }
               }
               resultList.add(t);
           }
       } else {
           throw new RuntimeException("sheetName:" + this.sheetName + " is not exist");
       }
      

      } catch (InstantiationException e) {
      LOG.error(“初始化异常”, e);
      } catch (IllegalAccessException e) {
      LOG.error(“初始化异常”, e);
      } catch (ParseException e) {
      LOG.error(“时间格式化异常:{}”, e);
      } catch (Exception e) {
      LOG.error(“其他异常”, e);
      }finally {
      try {
      workbook.close();
      } catch (IOException e) {
      e.printStackTrace();
      }
      }
      return resultList;
      }

    private void getCellValue(Cell cell, Object o, Field field) throws IllegalAccessException, ParseException {
    LOG.debug(“cell:{}, field:{}, type:{}”, cell.getCellTypeEnum(), field.getName(), field.getType().getName());
    switch (cell.getCellTypeEnum()) {
    case BLANK:
    break;
    case BOOLEAN:
    field.setBoolean(o, cell.getBooleanCellValue());
    break;
    case ERROR:
    field.setByte(o, cell.getErrorCellValue());
    break;
    case FORMULA:
    field.set(o, cell.getCellFormula());
    break;
    case NUMERIC:
    if (DateUtil.isCellDateFormatted(cell)) {
    if (field.getType().getName().equals(Date.class.getName())) {
    field.set(o, cell.getDateCellValue());
    } else {
    field.set(o, format.format(cell.getDateCellValue()));
    }
    } else {
    if (field.getType().isAssignableFrom(Integer.class) || field.getType().getName().equals(“int”)) {
    field.setInt(o, (int) cell.getNumericCellValue());
    } else if (field.getType().isAssignableFrom(Short.class) || field.getType().getName().equals(“short”)) {
    field.setShort(o, (short) cell.getNumericCellValue());
    } else if (field.getType().isAssignableFrom(Float.class) || field.getType().getName().equals(“float”)) {
    field.setFloat(o, (float) cell.getNumericCellValue());
    } else if (field.getType().isAssignableFrom(Byte.class) || field.getType().getName().equals(“byte”)) {
    field.setByte(o, (byte) cell.getNumericCellValue());
    } else if (field.getType().isAssignableFrom(Double.class) || field.getType().getName().equals(“double”)) {
    field.setDouble(o, cell.getNumericCellValue());
    } else if (field.getType().isAssignableFrom(String.class)) {
    String s = String.valueOf(cell.getNumericCellValue());
    if (s.contains(“E”)) {
    s = s.trim();
    BigDecimal bigDecimal = new BigDecimal(s);
    s = bigDecimal.toPlainString();
    }
    //防止整数判定为浮点数
    if (s.endsWith(".0"))
    s = s.substring(0, s.indexOf(".0"));
    field.set(o, s);
    } else {
    field.set(o, cell.getNumericCellValue());
    }
    }
    break;
    case STRING:
    if (field.getType().getName().equals(Date.class.getName())) {
    field.set(o, format.parse(cell.getRichStringCellValue().getString()));
    } else {
    field.set(o, cell.getRichStringCellValue().getString());
    }
    break;
    default:
    field.set(o, cell.getStringCellValue());
    break;
    }
    }

    private Workbook createWorkbook() throws IOException, InvalidFormatException {
    Workbook workbook;
    File file = new File(this.excelFilePath);
    if (!file.exists()) {
    LOG.warn(“文件:{} 不存在!创建此文件!”, this.excelFilePath);
    if (!file.createNewFile()) {
    throw new IOException(“文件创建失败”);
    }
    workbook = new XSSFWorkbook();
    } else {
    workbook = WorkbookFactory.create(file);
    }
    return workbook;
    }

    /**

    • 将数据写入excel文件
    • @param list 数据列表
    • @param 泛型
    • @return 写入结果
      */
      public boolean createExcel(List list) {
      if (null == this.excelFilePath || “”.equals(this.excelFilePath))
      throw new NullPointerException(“excelFilePath is null”);
      boolean result = false;
      FileOutputStream fileOutputStream = null;
      if (null != list && !list.isEmpty()) {
      T test = list.get(0);
      Map<String, Field> fieldMap = new HashMap<String, Field>();
      Map<Integer, String> titleMap = new TreeMap<Integer, String>();
      Field[] fields = test.getClass().getDeclaredFields();
      for (Field field : fields) {
      if (field.isAnnotationPresent(MapperCell.class)) {
      MapperCell mapperCell = field.getAnnotation(MapperCell.class);
      fieldMap.put(mapperCell.cellName(), field);
      titleMap.put(mapperCell.order(), mapperCell.cellName());
      }
      }
      try {
      Sheet sheet = workbook.createSheet(this.sheetName);
      Collection values = titleMap.values();
      String[] s = new String[values.size()];
      values.toArray(s);
      //生成标题行
      Row titleRow = sheet.createRow(0);
      for (int i = 0; i < s.length; i++) {
      Cell cell = titleRow.createCell(i);
      cell.setCellValue(s[i]);
      }
      //生成数据行
      for (int i = 0, length = list.size(); i < length; i++) {
      Row row = sheet.createRow(i + 1);
      for (int j = 0; j < s.length; j++) {
      Cell cell = row.createCell(j);
      for (Map.Entry<String, Field> data : fieldMap.entrySet()) {
      if (data.getKey().equals(s[j])) {
      Field field = data.getValue();
      field.setAccessible(true);
      cell.setCellValue(field.get(list.get(i)).toString());
      break;
      }
      }
      }
      }
      File file = new File(this.excelFilePath);
      if (!file.exists()) {
      if (!file.createNewFile()) {
      throw new IOException(“文件创建失败”);
      }
      }
      fileOutputStream = new FileOutputStream(file);
      workbook.write(fileOutputStream);
      result = true;
      } catch (IOException e) {
      LOG.error(“流异常”, e);
      } catch (IllegalAccessException e) {
      LOG.error(“反射异常”, e);
      } catch (Exception e) {
      LOG.error(“其他异常”, e);
      } finally {
      if (null != fileOutputStream) {
      try {
      fileOutputStream.close();
      } catch (IOException e) {
      LOG.error(“关闭流异常”, e);
      }
      }
      }
      }
      return result;
      }

    /**

    • 获取指定单元格的值
    • @param rowNumber 行数,从1开始
    • @param cellNumber 列数,从1开始
    • @return 该单元格的值
      */
      public String getCellValue(int rowNumber, int cellNumber) {
      String result;
      checkRowAndCell(rowNumber, cellNumber);
      Sheet sheet = this.workbook.getSheet(this.sheetName);
      Row row = sheet.getRow(–rowNumber);
      Cell cell = row.getCell(–cellNumber);
      switch (cell.getCellTypeEnum()) {
      case BLANK:
      result = cell.getStringCellValue();
      break;
      case BOOLEAN:
      result = String.valueOf(cell.getBooleanCellValue());
      break;
      case ERROR:
      result = String.valueOf(cell.getErrorCellValue());
      break;
      case FORMULA:
      result = cell.getCellFormula();
      break;
      case NUMERIC:
      if (DateUtil.isCellDateFormatted(cell)) {
      result = format.format(cell.getDateCellValue());
      } else {
      result = String.valueOf(cell.getNumericCellValue());
      }
      break;
      case STRING:
      result = cell.getRichStringCellValue().getString();
      break;
      default:
      result = cell.getStringCellValue();
      break;
      }
      return result;
      }

    @Override
    public void close() throws IOException {
    this.workbook.close();
    }

    private void checkRowAndCell(int rowNumber, int cellNumber) {
    if (rowNumber < 1) {
    throw new RuntimeException(“rowNumber less than 1”);
    }
    if (cellNumber < 1) {
    throw new RuntimeException(“cellNumber less than 1”);
    }
    }
    }

检验表头

package com.ixilink.common.utils;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.
;

/**

  • Excel转化为data数据 目前仅支持本地文件 及 附属工具
    */
    public class ExcelToData {

    private String fileName;
    private String filePath;

    public ExcelToData() {

    };

    public ExcelToData(String fileName, String filePath) {
    this.fileName = fileName;
    this.filePath = filePath;
    }

    /**

    • 获取第一个工作表名
    • @return
      */
      public String getFirstSheetName() {
      Workbook wb = null;
      Sheet sheet = null;
      wb = readExcel(fileName, filePath);
      try {
      wb.close();
      } catch (IOException e) {
      e.printStackTrace();
      }
      if (wb != null) {
      // 获取第一个sheet
      sheet = wb.getSheetAt(0);
      return sheet.getSheetName();
      }
      return “Sheet1”;

    }

    /**

    • 校验表头

    • @return
      */
      public List checkHead() {
      Workbook wb = null;
      Sheet sheet = null;
      Row row = null;
      List<Map<String, String>> list = null;
      String cellData = null;
      wb = readExcel(fileName, filePath);
      try {
      wb.close();
      } catch (IOException e) {
      e.printStackTrace();
      }
      List heads = new ArrayList();
      if (wb != null) {
      // 用来存放表中数据
      list = new ArrayList<Map<String, String>>();
      // 获取第一个sheet
      sheet = wb.getSheetAt(0);
      // 获取最大行数
      int rownum = sheet.getPhysicalNumberOfRows();
      // 获取第一行
      row = sheet.getRow(0);
      if(row == null) {
      return heads;
      }
      // 获取最大列数
      int colnum = row.getPhysicalNumberOfCells();

       for (int i = 0; i < rownum; i++) {
       	Map<String, String> map = new LinkedHashMap<String, String>();
       	row = sheet.getRow(i);
       	if (row != null) {
       		for (int j = 0; j < colnum; j++) {
       			if (i == 0) {
       				heads.add(getCellFormatValue(row.getCell(j)).toString().trim());
       			}
       		}
       	}
       }
      

      }
      return heads;

    }

    /**

    • 获取每行数据集合
    • @param fileName
    •        String 文件绝对地址
      
    • @return String[] 数据集合
      */
      public String[] getRowsData() {
      Workbook wb = null;
      Sheet sheet = null;
      Row row = null;
      List<Map<String, String>> list = null;
      String cellData = null;
      wb = readExcel(fileName, filePath);
      try {
      wb.close();
      } catch (IOException e) {
      e.printStackTrace();
      }
      if (wb != null) {
      // 用来存放表中数据
      list = new ArrayList<Map<String, String>>();
      // 获取第一个sheet
      sheet = wb.getSheetAt(0);
      // 获取最大行数
      int rownum = sheet.getPhysicalNumberOfRows();
      // 获取第一行
      row = sheet.getRow(0);
      // 获取最大列数
      int colnum = row.getPhysicalNumberOfCells();
      StringBuffer sb_columnsNames = new StringBuffer();
      for (int i = 0; i < rownum; i++) {
      Map<String, String> map = new LinkedHashMap<String, String>();
      row = sheet.getRow(i);
      if (row != null) {
      for (int j = 0; j < colnum; j++) {
      if (i == 0) {
      sb_columnsNames.append((String) getCellFormatValue(row.getCell(j)) + “;”);
      } else {
      cellData = (String) getCellFormatValue(row.getCell(j));
      map.put(sb_columnsNames.toString().split(";")[j], cellData);
      }
      }
      } else {
      break;
      }
      list.add(map);
      }
      }
      StringBuffer result = new StringBuffer();
      // 遍历解析出来的list
      for (Map<String, String> map : list) {
      Set<Map.Entry<String, String>> set = map.entrySet();
      int index = set.size() - 1;
      for (Map.Entry<String, String> entry : set) {
      if (index == 0) {
      result.append(entry.getKey() + “:” + entry.getValue() + “;”);
      break;
      }
      result.append(entry.getKey() + “:” + entry.getValue() + “,”);
      –index;
      }
      }
      return result.toString().split(";");
      }

    // 读取excel
    @SuppressWarnings(“resource”)
    private Workbook readExcel(String fileName, String filePath){
    Workbook wb = null;
    if (fileName == null) {
    return null;
    }
    String extString = fileName.substring(fileName.lastIndexOf("."));
    InputStream is = null;
    try {
    is = new FileInputStream(filePath + “\” + fileName);
    // if (".xls".equals(extString)) {
    // return wb = new HSSFWorkbook(is);
    // } else if (".xlsx".equals(extString)) {
    // return wb = new XSSFWorkbook(is);
    // } else {
    // return wb = null;
    // }
    try {
    wb = WorkbookFactory.create(is);
    } catch (EncryptedDocumentException e) {
    e.printStackTrace();
    } catch (InvalidFormatException e) {
    e.printStackTrace();
    }

     } catch (FileNotFoundException e) {
     	e.printStackTrace();
     } catch (IOException e) {
     	e.printStackTrace();
     }finally {
     	try {
     		wb.close();
     		is.close();
    
     	} catch (IOException e) {
     		e.printStackTrace();
     	}
     }
     return wb;
    

    }

    private Object getCellFormatValue(Cell cell) {
    Object cellValue = null;
    if (cell != null) {
    // 判断cell类型
    switch (cell.getCellTypeEnum()) {
    case NUMERIC: {
    if (DateUtil.isCellDateFormatted(cell)) {
    Date date = cell.getDateCellValue();
    DateFormat formater = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
    cellValue = formater.format(date);
    break;
    } else if (String.valueOf(cell.getNumericCellValue()).contains(".")) {
    DecimalFormat df = new DecimalFormat("#");
    cellValue = df.format(cell.getNumericCellValue());
    cellValue = String.valueOf(cell.getNumericCellValue());
    break;
    }
    }
    case STRING: {
    cellValue = cell.getRichStringCellValue().getString();
    break;
    }
    default:
    cellValue = “”;
    }
    } else {
    cellValue = “”;
    }
    return cellValue;
    }

    /**

    • 获取随机文件夹名称
    • @param inName
    •        StringBuffer
      
    • @return StringBuffer
      */
      public static StringBuffer getName(StringBuffer inName,String username) {
      return inName.replace(0, inName.indexOf("."), ExcelToData.getRandomString(10)+"-"+username);
      }

    private static String string = “abcdefghijklmnopqrstuvwxyz”;

    /** 获取指定长度随机字符串-带年月日 */
    public static String getRandomString(int length) {
    Random r = new Random();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < length; i++) {
    sb.append(string.charAt(r.nextInt(string.length() - 1)));
    }
    SimpleDateFormat df = new SimpleDateFormat(“yyyy-MM-dd”);//设置日期格式
    Date date = new Date(System.currentTimeMillis());
    return df.format(date)+"-"+sb.toString();
    }

    /** 获取指定长度随机字符串 */
    public static String getRandomStr(int length) {
    Random r = new Random();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < length; i++) {
    sb.append(string.charAt(r.nextInt(string.length() - 1)));
    }
    return sb.toString();
    }

    /**

    • 后缀名对照 只能上传Excel表格文件
    • @param inName
    •        StringBuffer
      
    • @return boolean
      */
      public static boolean compare(StringBuffer inName) {
      String str = inName.substring(inName.indexOf(".") + 1);
      if (!“xls”.equals(str) && !“xlsx”.equals(str)) {
      return true;
      }
      return false;
      }

    /**

    • 删除指定目录文件
    • @param path
    •        String
      

    */
    public void deleteFile(String path) {
    File file = new File(path);
    boolean exists = file.exists();
    boolean result = false;
    int tryCount = 0;
    while(!result && tryCount++ <10)
    {
    System.gc();
    result = file.delete();
    }
    //boolean delete = file.delete();
    //System.out.println(delete);
    }

    /** 补0 */
    private static String coveringPosition(String str, Integer index) {
    StringBuilder sb = new StringBuilder(str);
    while (sb.length() < index) {
    sb.insert(0, “0”).toString();
    }
    return sb.toString();

    }

}

方法测试
FastExcel fastExcel =null;
try {
//用构造方法把文件传入到工具类中
fastExcel=new FastExcel(path + “\” + fileName.toString());
//工作簿设置名字
fastExcel.setSheetName(sheetName);
//根据excel的数据,把Excel的数据封装进ArchivesTransferEntity类里去
tests = fastExcel.parse(ArchivesTransferEntity.class);
if (null != tests && !tests.isEmpty()) {

			// 批量导入数据
			Map<String, Object> param = new HashMap<>();

// param.put(“statusFlag”, statusFlag);
param.put(“list”, tests);
// param.put(“deleteStatus”, 0);
num = ArchivesTransferDao.updatecheckBatch(param);
ArchivesTransferDao.checkBatch(param);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值