Excel导入(详)

要做排班导入的功能,在点击导入时不跳转后台,直接跳转到另一个html页面,但是要携带值过去,

点击事件,通过路径地址直接传值,

在另一页面 直接通过 gteUrlParam 方法 就能获取到值。

 

1 先看 前台html页面,前台导入的文件()

然后 js文件 表单提交

$(function () {
    var str =   getUrlParam("queryId");
    //form表单提交 文件
    var form = $("#form-admin-edit");
    form.validate({
        submitHandler: function () {

            var formData = new FormData();
            var textdatas = form.serializeArray();
            $.each(textdatas, function () {
                if (this.name) {
                    formData.append(this.name, this.value);
                }
            });
            formData.append("dutyfile", $("#dutyfile")[0].files[0]);
            addFileSubmit(formData, "/duty/importExcel?queryId="+str);
        }
    })
})

进入后台代码段

//导入排班
    @RequestMapping(value = "/importExcel")
    public MsgResponse importExcel(HttpServletRequest request, MultipartFile dutyfile, String queryId) throws Exception {
        //List<String> errorList = new ArrayList<String>();
        //班组id
        int teamId = Integer.valueOf(queryId);
        Date date1 = null;
        Date date2 = null;
//读取excel文件的工具类
        ImportExcelUtil util = new ImportExcelUtil();
        InputStream input = null;
        List<List<Object>> lists = null;
        if (dutyfile.isEmpty()) {
            log.error("文件不存在");
            return MsgResponse.fail("未选择文件");
        } else {
            String fileName = dutyfile.getOriginalFilename();
            input = dutyfile.getInputStream();
            //解析excel 返回的是嵌套集合
            lists = util.getBankListByExcel(input, fileName);
            input.close();
            //得到传入的表头,根据表头获得当前排班表的起始时间
            String title = util.getFormat(String.valueOf(lists.get(0)));
            //根据括号截取出时间范围 如 (2018-07-09—2018-07-15)
            int s = title.indexOf("(");
            int b = title.indexOf(")");
            //表头显示的一周时间范围
            String weekdate = title.substring(s + 1, b);
//            System.out.println("一周时间" + weekdate);
            String beginTime = weekdate.substring(0, 10);
//            System.out.println("起始时间" + beginTime);
            String endDate = weekdate.substring(11);
//            System.out.println("结束时间" + endDate);
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//            将开始及结束时间转换为Date类型
            date1 = format.parse(beginTime);
            date2 = format.parse(endDate);
            //findDates方法 返回的是一个集合时间段如
              /**  时间范围::2018-07-09—2018-07-12
                开始时间2018-07-09
                结束时间2018-07-12
                返回的时间集合
                2018-07-09
                2018-07-10
                2018-07-11
                2018-07-12
                */
            List<Date> lsDate = findDates(date1, date2);
            System.out.println("嵌套集合" + lists);
            List<HashMap<String, Object>> dutyNameList = new ArrayList<>();
            //循环将excel中的数据存入库
            for (int i = 2; i < lists.size(); i++) {
                //得到当前Excel中每一行的数据,(i=0位表头,等于1为第二行即各列的列名,从2开始为传入的数据)
                List<Object> list = lists.get(i);
//                      System.out.println("当前传入excel里的参数为"+list);
                //遍历当前行当中 第一列的值
//                      for (int j=0;j<1;j++){
//                            System.out.println("名字为:"+util.getFormat(String.valueOf(list.get(0)))+"!");
//                            //将第一列的名字放置集合里
//                            nameList.add(util.getFormat(String.valueOf(list.get(0))));
//                      }
                String name = "";
                if (list.size() > 0) {
                    name = util.getFormat(String.valueOf(list.get(0)));
                }
                //遍历当前行中,第二列到最后所有列的值,周一~周末
                for (int j = 1; j < list.size(); j++) {
//                    System.out.print("周一至周末的班次名称为:" + util.getFormat(String.valueOf(list.get(j))) + "\t");
                    String dutyName = "";
                    Date dutyTime = null;
                    if (lsDate.size() == list.size() - 1 && null != lsDate.get(j - 1)) {
                        dutyTime = lsDate.get(j - 1);
                    }
                    if (!Tool.isEmpty(list.get(j)) && !Tool.isEmpty(name) && !Tool.isEmpty(dutyTime) ) {
                        dutyName = (String) list.get(j);
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("name", name);
                        map.put("dutyName", dutyName);
                        map.put("dutyTime", dutyTime);
                        dutyNameList.add(map);
                    }
                }
            }
            String wardCode = "";
            for (int i = 0; i < dutyNameList.size(); i++) {
                HashMap<String, Object> map = dutyNameList.get(i);
                String name = (String) map.get("name");
                if (Tool.isEmpty(wardCode)) {
                    wardCode = dutyService.selectDutyNameWardCode(name.trim());
                    System.out.print("病区代码" + wardCode);
                }
                String teamUserCode= dutyService.selectTeamUserCode((String) map.get("name"));
                ZvDutyRoster roster = new ZvDutyRoster();
                roster.setTeamusername(name);
                roster.setRosterdate((Date) map.get("dutyTime"));
                roster.setTeamusercode(teamUserCode);
                roster.setWardcode(wardCode);
                roster.setTeamid(teamId);
                Integer classId = dutyService.selectDutyClassName(((String) map.get("dutyName")).trim());
//                System.out.println("姓名:"+roster.getTeamusername()+"时间:"+(Date)map.get("dutyTime"));
//                System.out.print("班次id"+classId);
//                System.out.println("班次名称"+(String)map.get("dutyName"));
                ZvDutyRoster zvd =  dutyService.selectDuty(teamUserCode,(Date) map.get("dutyTime"));
                //如果不为空
                if(!Tool.isEmpty(zvd)){
                    zvd.setClassid(roster.getClassid());
                    int result = dutyService.updateDuty(zvd);
                }else {
                    if (classId != null && classId > 0) {
                        roster.setClassid(classId);
                        int res = dutyService.insertDutyRoster(roster);
                    }
                }

            }
        }
        return MsgResponse.success();
    }


 /**
     * 获取某段时间里的每一天的日期集合
     *
     * @param dBegin
     * @param dEnd
     * @return
     */
    public static List<Date> findDates(Date dBegin, Date dEnd) {
        List<Date> lDate = new ArrayList<Date>();
        lDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        return lDate;
    }

 

excel导入工具类:

package com.zenvans.zvmng.tool;


import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFWorkbook;

/**
 * excel文件上传Util
 *
 * @author Justin
 *
 */

public class ImportExcelUtil {

    private final static String Excel_2003 = ".xls"; //2003 版本的excel
    private final static String Excel_2007 = ".xlsx"; //2007 版本的excel

    /**
     * @param in
     * @param fileName
     * @param
     * @return
     */
    public List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception {
        List<List<Object>> list = null;

        //创建Excel工作簿
        Workbook work = this.getWorkbook(in, fileName);
        if (work == null) {
            throw new Exception("创建Excel工作簿为空!");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;

        list = new ArrayList<List<Object>>();
        //遍历Excel中的所有sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            //遍历当前sheet中的所有行
            int totalRow = sheet.getPhysicalNumberOfRows();//如果excel有格式,这种方式取值不准确
           // int totalRow = sheet.getPhysicalNumberOfRows();
            for (int j = sheet.getFirstRowNum(); j < totalRow; j++) {
                row = sheet.getRow(j);
                if (row != null && !"".equals(row)) {
                    //获取第一个单元格的数据是否存在
                    Cell fristCell = row.getCell(0);
                    if (fristCell != null) {
                        //遍历所有的列
                        List<Object> li = new ArrayList<Object>();
                        //int totalColum = row.getLastCellNum();
                        for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                            cell = row.getCell(y);
                            String callCal = this.getCellValue(cell) + "";
                            li.add(callCal);
                        }
                        list.add(li);
                    }
                }

            }
        }
        in.close();
        return list;
    }

    /**
     * 描述:根据文件后缀,自动适应上传文件的版本
     *
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook work = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (Excel_2003.equals(fileType)) {
            work = new HSSFWorkbook(inStr);//2003 版本的excel
        } else if (Excel_2007.equals(fileType)) {
            work = new XSSFWorkbook(inStr);//2007 版本的excel
        } else {
            throw new Exception("解析文件格式有误!");
        }
        return work;
    }

    /**
     * 描述:对表格中数值进行格式化
     *
     * @param cell
     * @return
     */
    public Object getCellValue(Cell cell) {
        Object value = null;
        DecimalFormat df1 = new DecimalFormat("0");//格式化number,string字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");//日期格式化
        DecimalFormat df2 = new DecimalFormat("0.00");//格式化数字
        if (cell != null && !"".equals(cell)) {
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    value = cell.getRichStringCellValue().getString();
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                        value = df1.format(cell.getNumericCellValue());
                    } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                        value = sdf.format(cell.getDateCellValue());
                    } else if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        value = sdf.format(date);
                    } else {
                        value = df2.format(cell.getNumericCellValue());
                    }
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    value = cell.getBooleanCellValue();
                    break;
                case Cell.CELL_TYPE_BLANK:
                    value = "";
                    break;
                default:
                    break;
            }
        }
        return value;
    }

    public String getFormat(String str) {
        if (str.equals("null")) {
            str = "";
            return str;
        } else {
            return str;
        }
    }

    public Integer getFormats(Integer str) {
        if (str == null) {
            str = 0;
            return str;
        } else {
            return str;
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值