上传Excel数据到mongo

Excel第一行为数据列的 key, 第二行为数据列的数据类型
Controller
@RequestMapping(value="/data/import", method=RequestMethod.POST)
public Message importOpenStrategyData(
        @RequestParam(value="collectionName") String collectionName,
        @RequestParam(value="file", required = false) MultipartFile file) {

    try {
        if(file == null || file.isEmpty() || file.getBytes().length == 0 || file.getSize() == 0) {
            throw new HException(HErrorCode.ARGUMENT_ILLEGAL, "导入文件为空");
        }
        if(!file.getOriginalFilename().endsWith(".xlsx")) {
            throw new HException(HErrorCode.ARGUMENT_ILLEGAL, "请导入Excel(*.xlsx)文件");
        }
        File tempFile = SysService.createTempFile();//创建临时文件
        file.transferTo(tempFile);
        return Message.createSuccessMessage(openStrategyService.importOpenStrategyData(collectionName, tempFile));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        throw new HException(HErrorCode.ARGUMENT_ILLEGAL, "文件格式有问题,请检查");
    }
Service
public String importOpenStrategyData(String collectionName, File file) {
    
    InputStream is = null;
    XSSFWorkbook book = null;
    long total = 0L;// 统计导入数据条数
    long exceptinNums = 0L;// 异常数据条数
    try {

        is = new FileInputStream(file);
        book = new XSSFWorkbook(is);
        XSSFSheet sheet = book.getSheetAt(0);
        // 获取总共的行数
        int rowNums = sheet.getLastRowNum();
        if(rowNums <= 2) {
            throw new HException(HErrorCode.ARGUMENT_ILLEGAL, "导入文件为空");
        }
        // 获取列名称及各列对应的数据类型
        Row titleRow = sheet.getRow(0);//第一行为td_name
        Row typeRow = sheet.getRow(1);//第二行为td_type
        if(titleRow == null || typeRow == null) {
            throw new HException(HErrorCode.ARGUMENT_ILLEGAL, "数据列名称和数据类型不能为空");
        }
        int titleColNums = titleRow.getLastCellNum();
        int typeColNums = typeRow.getLastCellNum();
        if(titleColNums != typeColNums) {
            throw new HException(HErrorCode.ARGUMENT_ILLEGAL, "数据列名称和数据类型不能完全匹配");
        }
        // colName,colType存放在数组
        List colNames = new ArrayList<>();
        List colTypes = new ArrayList<>();
        for(int i = 0; i

你可能感兴趣的:(Java,EE)