批量上传Excel文件


  1.jsp中代码
  <form  id="uploadForm" method="post" action ="${ctx}/trainingSchedule/upFile.do" enctype ="multipart/form-data" target='uploadframe' >
            <input type="file" name="file1" id="fileName" class="mini-htmlfile"  limitType="*.xls;*.xlsx">
            <button  style="margin-left: 30px;" class="mini-button" iconCls="icon-upload" οnclick="onUpload()">上传</button>
            <br>
            <br>
            <a href="${ctx}/static/exceltemplate/TrainingSchedule.xls">点击此处进行模板文件下载</a>
            <small style="margin-left: 50px;">备注:文件大小请控制在1M以内,文件支持为.xls格式数据</small>
            
    </form>
  2js中代码:
  function onUpload(){
 var file=mini.get("fileName").getValue();
 if(file==""||file==null){
      mini.alert("请选择要上传的文件!");
      return false; 
 }else{
     $("#uploadForm").submit();
 }
}


  3.controller中代码

    @RequestMapping("/upFile.do")
    @ResponseBody
    public ModelAndView Upload(HttpServletRequest request, HttpServletResponse response) {
        logger.info("===============批量上传业务处理开始=================");
        ResultDTO resultDTO = new ResultDTO();
        // 封转返回页面和数据
        ModelAndView modelAndView = new ModelAndView();
        // 创建一个通用的多部分解析器.
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 设置编码
        commonsMultipartResolver.setDefaultEncoding("gbk");

        // 判断 request 是否有文件上传,即多部分请求...
        if (commonsMultipartResolver.isMultipart(request)) {
            // 转换成多部分request
            MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart(request);

            // file 是指 文件上传标签的 name=值
            // 根据 name 获取上传的文件...
            MultipartFile file = multipartRequest.getFile("file1");
            String fileName = null;
            InputStream ins = null;
  try {
                fileName = file.getOriginalFilename();
                String fileExtends = fileName.split("\\.")[fileName.split("\\.").length - 1];
                if (!"xls".equals(fileExtends)) {
                    logger.error("必须上传  .xls 格式的Excel文件");
                    throw new BusinessException("必须上传  .xls 格式的Excel文件");
                }
                ins = file.getInputStream();
                String flag = trainingScheduleService.upload(ins, fileName);
                modelAndView.addObject("text", flag);
                modelAndView.setViewName("/schedule/scheduleError");
            } catch (BusinessException e) {
                modelAndView.addObject("text", e.getMessage());
                modelAndView.setViewName("/schedule/scheduleError");
                logger.error(e.getMessage());
            } catch (IOException e) {
                modelAndView.addObject("text", "处理文件失败");
                modelAndView.setViewName("/schedule/scheduleError");
                e.printStackTrace();
            } catch (Exception e) {
                modelAndView.addObject("text", "处理文件失败");
                modelAndView.setViewName("/schedule/scheduleError");
                e.printStackTrace();
            } finally {
                if (ins != null) {
                    try {
                        ins.close();
                    } catch (IOException e) {
                    logger.error(e.getMessage());
                    }
                }
            }
        }
        logger.info("================批量上传业务处理结束==============");
        return modelAndView;

    }
 

 

4.ServiceImpl中代码

public String upload(InputStream ins, String fileName) throws Exception {
        InputStream sbs = null;
        Workbook book = null;
        // String batchNo = null;

        try {
            String userId = SessionUtil.getUser().getUserId();
            // String userId =
            // manageUserService.getCurrentUserInfo().getUserId();
            logger.info("当前操作用户为:" + userId);
            byte[] b = null;
            try {
                b = toByteArray(ins);
            } catch (Exception e) {
                e.printStackTrace();
            } // 把流转换为数组

            logger.info("Excel文件已经保存到本地磁盘中");

            // batchNo = "B" + DateUtil.getCurrentDate("yyyyMMddHHmmsssss");

            // 保存文件
            saveFile(b, fileName);

            TrainingSchedule trainingSchedule = new TrainingSchedule();
            // trainingSchedule.setTransNo(batchNo);
            // trainingSchedule.setFileName(fileName);
            trainingSchedule.setCreateUser(userId);
            trainingSchedule.setCreateDate(DateUtil.getCurrentDateTime());

            sbs = new ByteArrayInputStream(b);
            try {
                book = Workbook.getWorkbook(sbs);
            } catch (BiffException e) {
                e.printStackTrace();
            }
  // 打开文件
            Sheet sheet = book.getSheet(0);

            for (int i = 1; i < sheet.getRows(); i++) {
                // 从Excel中取出信息
                String serialNumber = sheet.getCell(0, i).getContents().trim(); // 编号
                if (serialNumber == null || "".equals(serialNumber.trim())) {
                    throw new BusinessException("请确认上传文件与模板Excel文件格式一致!");
                }
                String annual = sheet.getCell(1, i).getContents().trim();
                String manage_com = sheet.getCell(2, i).getContents().trim();
                String class_type = sheet.getCell(3, i).getContents().trim();
                String annual_target = sheet.getCell(4, i).getContents().trim();

                // 上传重复的文件,先查询是否有这个文件,有的话就会将之前的文件进行覆盖,将之前的数据状态改为“无效”
                TrainingScheduleExample example = new TrainingScheduleExample();
                TrainingScheduleExample.Criteria criteria = example.createCriteria();
                criteria.andAnnualEqualTo(annual).andManageComEqualTo(manage_com).andClassTypeEqualTo(class_type)
                        .andScheduleStateEqualTo("1");

                List<TrainingSchedule> list = trainingScheduleMapper.selectByExample(example);
                if (list != null) {
                    for (int j = 0; j < list.size(); j++) {
                        TrainingSchedule trainingSchedule1 = list.get(j);
                        trainingSchedule1.setScheduleState("0");
                        trainingScheduleMapper.updateByPrimaryKey(trainingSchedule1);
                    }
                }
  trainingSchedule.setAnnual(annual);
                trainingSchedule.setManageCom(manage_com);
                trainingSchedule.setClassType(class_type);
                trainingSchedule.setAnnualTarget(annual_target);
                trainingSchedule.setCreateUser(userId);
                trainingSchedule.setCreateDate(DateUtil.getCurrentDateTime());
                trainingSchedule.setScheduleState("1"); // 初始值默认为有效;

                // 对manage_com与class_type两个字段进行数据校验
                verifyData(trainingSchedule, serialNumber) ;
                // 数据校验通过后才可以保存明细和保存数据库还有本地磁盘

             trainingScheduleMapper.insert(trainingSchedule);

                logger.info("Excel内容明细已经保存到数据库中");
            }
            // trainingScheduleMapper.insert(anhuiSelfcard);
        } catch (IOException e) {
  } catch (BusinessException e) {
            throw new BusinessException(e.getMessage());
        } finally {
            try {
                sbs.close();
            } catch (IOException e) {
                logger.info("文件流关闭异常!");
                e.printStackTrace();
            }
            try {
                book.close();
            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("批量上传文件解析失败!");
            }
        }

        return "上传成功!";
    }


  数据校验代码
  private void verifyData(TrainingSchedule trainingSchedule, String serialNumber) {
        logger.info("********************数据合法性校验,接收参数:" + trainingSchedule);
        String manageCom = trainingSchedule.getManageCom();
        String classType = trainingSchedule.getClassType();

        DefCodeInfoExample example = new DefCodeInfoExample();
        DefCodeInfoExample.Criteria criteria = example.createCriteria();
        criteria.andCodeEqualTo(classType).andCodeTypeEqualTo("class_type");

        List<DefCodeInfo> list = defCodeInfoMapper.selectByExample(example);
    
        if (list.size() == 0) {
            throw new BusinessException("类型为" + classType + " 的数据不存在!上传失败!");
        } else {

            ManagecomInfoExample example1 = new ManagecomInfoExample();
            ManagecomInfoExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andManageComEqualTo(manageCom);

            List<ManagecomInfo> list1 = managecomInfoMapper.selectByExample(example1);
            if (list1.size() == 0) {

           throw new BusinessException("机构为" + manageCom + " 的机构不存在!上传失败!");
            }
        }

    }
}
 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
由于不知道你使用的编程语言和具体的需求,以下提供两种常见语言的代码示例供参考: Python: ```python import os import glob import pandas as pd # 设置要上传文件夹路径 folder_path = '/path/to/folder' # 获取文件夹下所有的Excel文件 files = glob.glob(os.path.join(folder_path, '*.xlsx')) # 读取每个Excel文件并合并为一个DataFrame df = pd.concat([pd.read_excel(f) for f in files], ignore_index=True) # 将合并后的DataFrame上传到数据库或其他存储介质中 # TODO: Write your code here ``` 上述代码使用了Python的glob和pandas库,通过glob获取文件夹下所有的Excel文件路径,然后使用pandas的read_excel方法读取每个Excel文件并合并为一个DataFrame,最后将合并后的DataFrame上传到数据库或其他存储介质中。 Java: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.poi.ss.usermodel.Cell; 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; public class ExcelUploader { public static void main(String[] args) throws IOException { // 设置要上传文件夹路径 String folderPath = "/path/to/folder"; // 获取文件夹下所有的Excel文件 List<File> files = getExcelFiles(new File(folderPath)); // 读取每个Excel文件并合并为一个List List<List<String>> data = new ArrayList<>(); for (File file : files) { data.addAll(readExcel(file)); } // 将合并后的List上传到数据库或其他存储介质中 // TODO: Write your code here } private static List<File> getExcelFiles(File folder) { List<File> files = new ArrayList<>(); for (File file : folder.listFiles()) { if (file.isFile() && file.getName().endsWith(".xlsx")) { files.add(file); } } return files; } private static List<List<String>> readExcel(File file) throws IOException { List<List<String>> data = new ArrayList<>(); try (FileInputStream fis = new FileInputStream(file); Workbook workbook = WorkbookFactory.create(fis)) { Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { List<String> rowData = new ArrayList<>(); for (Cell cell : row) { rowData.add(cell.toString()); } data.add(rowData); } } return data; } } ``` 上述代码使用了Java的Apache POI库,通过递归遍历文件夹获取所有的Excel文件路径,然后使用POI的WorkbookFactory和Sheet、Row、Cell等类读取每个Excel文件中的数据,并将其合并为一个List。最后将合并后的List上传到数据库或其他存储介质中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值